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

user1444393
  • 213
  • 1
  • 4
  • 17
  • 4
    Does this answer your question? [Flutter Error: MediaQuery.of() called with a context that does not contain a MediaQuery](https://stackoverflow.com/questions/50214338/flutter-error-mediaquery-of-called-with-a-context-that-does-not-contain-a-med) – Simon Sot Apr 05 '21 at 20:39

1 Answers1

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

Tamir Abutbul
  • 7,301
  • 7
  • 25
  • 53
Sheruan Bashar
  • 506
  • 4
  • 7
  • 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! – Brad Cypert Apr 05 '21 at 23:43