flutterdart

Cant use MediaQuery.of(context) for Themes in Flutter


Hi I am trying to create several TextTheme and change the fonts sizes using MediaQuery.of(context) based on this article:

Flutter — Effectively scale UI according to different screen sizes

But I am getting this error:

MediaQuery.of() called with a context that does not contain a MediaQuery.

I know based on this post: Flutter Error: MediaQuery.of() called with a context that does not contain a MediaQuery

I should use MediaQuery on my HomePage but then I cannot create themes using MediaQuery then?

Here is my code:

  child:
    MaterialApp(
            theme: ThemeData(
                /// TextFields Handlers transparent
                textSelectionHandleColor: Colors.transparent,
                pageTransitionsTheme: const PageTransitionsTheme(
                  builders: <TargetPlatform, PageTransitionsBuilder>{
                    TargetPlatform.android: ZoomPageTransitionsBuilder(),
                  },
                ),
                textTheme: TextTheme(
                  /// Pages Titles
                  headline1: textTheme(
                    fontSize: (MediaQuery.of(context).size.width / 100) * 1.5,
                    fontWeight: FontWeight.w600,
                    color: Globals.allColors['celeste'],
                  ),
                  headline2: textTheme(
                      fontSize: 15,
                      fontWeight: FontWeight.w600,
                      color: Globals.allColors['cetaceanBlue']),
                      ...

The error is at:

(MediaQuery.of(context).size.width / 100) * 1.5,

Thanks in advance!


Solution

  • No, you cannot create your material theme with values retrieved from Mediaquery. You set 'default' font size, etc. in your material app theme data. Then in your home page build method you call Mediaquery and modify your font size for that page if necessary.