uniflex
uniflex

Reputation: 23

MediaQuery.of() called with a context that does not contain a MediaQuery even when Wrapped under the MaterialApp Widget

I can't access the MediaQuery.of() in the MaterialApp widget within the themeData method referencing the screenHeight & screenWidth variables.

I've tried to wrap the HomeScreen widget within a MaterialApp widget itself followed by a Scaffold widget, but this did not help.

class MyApp extends StatelessWidget {
  MyApp({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {

    final screenHeight = MediaQuery.of(context).size.height / 100;
    final screenWidth = MediaQuery.of(context).size.width / 100;

    return MaterialApp(
      title: 'MyApp',
      theme: ThemeData(
        primaryColor: Color.fromRGBO(231, 13, 61, 1),
        textTheme: new TextTheme(
          title: new TextStyle(color: Colors.black, fontWeight: FontWeight.bold, fontSize: screenHeight * 1.8,),
          body1: new TextStyle(color: Colors.black, fontSize: screenHeight * 1.8,),

        ),

      ),
      home: HomeScreen(),
    );
  }
}

class _HomeScreen extends State {
  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppNavBar(),

      body: Container(
        color: Colors.white,
        child: ListView(
          children: <Widget> [
            new Page1Widget(),
            Divider(height: 0, color: Colors.grey,),
            new Page2Widget(),
          ],
        ),
      ),
        bottomNavigationBar: new BottomNavBar(),

    );
  }
}

flutter: ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════ flutter: The following assertion was thrown building MyApp(dirty): flutter: MediaQuery.of() called with a context that does not contain a MediaQuery. flutter: No MediaQuery ancestor could be found starting from the context that was passed to MediaQuery.of(). flutter: This can happen because you do not have a WidgetsApp or MaterialApp widget (those widgets introduce flutter: a MediaQuery), or it can happen if the context you use comes from a widget above those widgets. flutter: The context used was: flutter: MyApp(dirty)

Upvotes: 1

Views: 1337

Answers (1)

R&#233;mi Rousselet
R&#233;mi Rousselet

Reputation: 276881

Only descendants of MediaQuery can access it. Which means you cannot build MaterialApp.theme based on theme.

If you need to, you can use MaterialApp.builder:

MaterialApp(
  builder: (context, child) {
    MediaQuery.of(context);
    return Theme(
      child: child,
    );
  },
  home: ...
)

Upvotes: 3

Related Questions