Hello Guys. Many times we Face Flutter Error: MediaQuery.of() called with a context that does not contain a MediaQuery. So in this tutorial, we are going to Solve this error.
Suppose This is My Code
return new Container(
height: MediaQuery.of(context).size.height,
decoration: BoxDecoration(
color: backgroundColor,
),
child: DecoratedBox(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.max,
children: <Widget>[
Center(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Container(height: 120.0, color: Colors.yellow, child: new ColorLoader2(color1: Colors.redAccent, color2: Colors.deepPurple, color3: Colors.green),),
],
),
)
],
),
decoration: BoxDecoration(
color: Colors.redAccent,
),
)
);
}
}
And I am facing error at this line
MediaQuery.of(context).size.height,
What is The problem ?
Reason behind this issue is MediaQuery Is used by Scaffolds internal component. Thats why it must be wrapped inside a widget which will provide us MediaQuery Something like MaterialApp Widget or WidgetsApp
. Material App Will Provide Mediaquery and that will solve our error.
Solution
Question: How to solve Flutter Error: MediaQuery.of() called with a context that does not contain a MediaQuery ?
Answer: Solution is MediaQuery.of(context) line must be in Material app -> scaffold -> MediaQuery.of(context). That’s why We have to use MaterialApp -> Scaffold And then We can use MediaQuery.of(context). Below Is My Example Code For Reference.
Solution is MediaQuery.of(context) line must be in Material app -> scaffold -> MediaQuery.of(context). That’s why We have to use MaterialApp -> Scaffold And then We can use MediaQuery.of(context). Below Is My Example Code For Reference.
void main() => runApp(App());
class App extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Title',
home: HomePage(),
);
}
}
class HomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
final size = MediaQuery.of(context).size;
return Container(
);
}
}
Now, Error is solved. If you still facing this error so Comment below your error with code. I Will help You. Comment below Your thoughts and your queries. And Also Comment on your suggestion here.
Also Read
- How to make a blur Background Image effect in Flutter using BackdropFilter.
- Create Rounded Corners Image in Flutter.