简体   繁体   中英

Getting Error in flutter MediaQuery.of() called with a context that does not contain a MediaQuery

I didn't understand what the error is. I am returning a Scaffold widget. There are no syntax errors detected by visual studio code. I am getting an error while running the app.


void main() {
runApp(MyApp());
}

class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
   appBar: AppBar(title: Text("here is my text")),
   body: Text(
     'No, we need bold strokes. We need this plan.',
     style: TextStyle(
         fontWeight: FontWeight.bold,
         color: Colors.blue.withOpacity(0.7),
         height: 1,
         fontSize: 20,
         decoration: TextDecoration.underline,
         decorationColor: Colors.green,
         decorationStyle: TextDecorationStyle.wavy,
         backgroundColor: Colors.red),
   ),
 );
}
}

If I wrap the scaffold widget in the material app it is working. Can anyone explain to me the reason?


void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text("here is my text")),
        body: Text(
          'No, we need bold strokes. We need this plan.',
          style: TextStyle(
              fontWeight: FontWeight.bold,
              color: Colors.blue.withOpacity(0.7),
              height: 1,
              fontSize: 20,
              decoration: TextDecoration.underline,
              decorationColor: Colors.green,
              decorationStyle: TextDecorationStyle.wavy,
              backgroundColor: Colors.red),
        ),
      ),
    );
  }
}

The top most widget must be wrapped in a MaterialApp widget. This is what generates the context chain that it's looking for.

Media Query is a property of MaterialApp so if you don't use the MaterialApp, you can't access media query. The proper way is to use it in your main class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM