Use ThemeData as theme for CupertinoApp

Issue

My app was built using a MaterialApp as the root widget. To this material app, I’ve added a theme as follows:

MaterialApp(
  theme: myTheme,
  home: MyHomePage(),
  ...
)

final ThemeData myTheme = _buildTheme();

ThemeData _buildTheme() {
  final ThemeData base = ThemeData.light();
  return base.copyWith(
    ...
      textTheme: _buildMyTextTheme(base.textTheme),
      primaryTextTheme: _buildMyTextTheme(base.primaryTextTheme),
      accentTextTheme: _buildMyTextTheme(base.accentTextTheme),
      pageTransitionsTheme: PageTransitionsTheme(builders: {
        TargetPlatform.iOS: CupertinoPageTransitionsBuilder(),
      }));
}

TextTheme _buildMyTextTheme(TextTheme base) {
  return base
      .copyWith(
        headline:
            base.headline.copyWith(fontSize: 20.0, fontWeight: FontWeight.w500),
        title: base.title.copyWith(fontSize: 18.0, fontWeight: FontWeight.w400),
        subhead:
            base.subhead.copyWith(fontSize: 16.0, fontWeight: FontWeight.w400),
        body1: base.body1.copyWith(fontSize: 14.0, fontWeight: FontWeight.w400),
        body2: base.body2.copyWith(fontSize: 14.0, fontWeight: FontWeight.w500),
        caption: base.caption.copyWith(
          fontWeight: FontWeight.w400,
          fontSize: 12.0,
        ),
      )
      .apply(
        fontFamily: 'myfont',
        displayColor: Colors.black,
        bodyColor: Colors.black,
      );
}

I’ve used Theme.of(context.textTheme to style the text in the whole app down the widget tree.

for example :
to a title I used

Text('Title', style:Theme.of(context).textTheme.title),

to a subtitle I used

Text('Title', style:Theme.of(context).textTheme.subhead),

It works as intended.
But now I want to use a CupertinoApp if the current platform is ios as it provides with native ios feel like

  • List item
  • Pages will be dismissible via a back swipe.
    Scrolling past extremities will trigger iOS-style spring overscrolls.

How shall I add the CupertionApp applying the same text theming?

Solution

you can wrap the CupertinoApp with Theme widget:

Theme(
   data: yourThemeData(), //your theme data here
   child: CupertinoApp(...),
);

Answered By – Karim Elghamry

Answer Checked By – Pedro (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *