MediaQuery.of() called with a context that does not contain a MediaQuery in flutter code example

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

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.

Example 2: media query flutter error

void main() => runApp(App());

class App extends StatelessWidget {
  
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Title',
      theme: kThemeData,
      home: HomePage(),
    );
  }
}

class HomePage extends StatelessWidget {
  
  Widget build(BuildContext context) {
    final size = MediaQuery.of(context).size;

    return Container(
      child: ...,
    );
  }
}

Tags:

Dart Example