1

I am facing, recently, this error in Flutter:

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

Here is my code:

import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; void main(){ runApp(Home()); } class Home extends StatefulWidget { @override _HomeState createState() => _HomeState(); } class _HomeState extends State<Home> { @override Widget build(BuildContext context) { final size = MediaQuery.of(context).size; return MaterialApp( title: 'Refresh my mind', debugShowCheckedModeBanner: false, theme: ThemeData( primarySwatch: Colors.red, ), home:Scaffold( appBar: AppBar( title: Text("Hello"), leading: Icon( Icons.ac_unit ), actions: [Icon(Icons.account_balance), Icon(Icons.airplanemode_active), Icon(Icons.autorenew),], elevation: 12, ), backgroundColor: Colors.teal, body: Container( color: Colors.black12, margin: EdgeInsets.all(20), child: Center( child: Card( elevation: 5.0, color: Colors.grey, child: Container( width: size.width/1.5, height: 200, ), ), ), ), ), ); } } 

I searched in the internet, and I found that i must used eather MaterialApp widget OR WidgetApp but i used the MaterialApp in my code.

So I am wondering, what's should be the mistake?

Thank you

1

1 Answer 1

1

That might be because MaterialApp is not initialized yet. Try to move your home widget to a separate file (e.g. home_screen.dart) and pass it to MaterialApp like:

MaterialApp(home:HomeScreen()) 

Inside your HomeScreen use MediaQuery

Sign up to request clarification or add additional context in comments.

1 Comment

Yup! Your context is coming from your MaterialApp in this case, so you wont be able to access the context until the MaterialApp is initialized!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.