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

后端 未结 14 1116
借酒劲吻你
借酒劲吻你 2020-11-28 14:05

I have been trying to get the size of the whole context view in Flutter. But every time I try I\'m getting the above mentioned error. Here\'s my code:

impor         


        
14条回答
  •  爱一瞬间的悲伤
    2020-11-28 14:45

    You need a MaterialApp or a WidgetsApp around your widget. They provide the MediaQuery. When you call .of(context) flutter will always look up the widget tree to find the widget.

    You usually have this in your main.dart:

    void main() => runApp(App());
    
    class App extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          title: 'Title',
          theme: kThemeData,
          home: HomePage(),
        );
      }
    }
    
    class HomePage extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        final size = MediaQuery.of(context).size;
    
        return Container(
          child: ...,
        );
      }
    }
    

提交回复
热议问题