How to fix "MediaQuery.of() called with a context that does not contain a MediaQuery." error in flutter?

07.08.2020 18:24
#FLUTTER #HATA #MEDİAQUERY

How to fix "MediaQuery.of() called with a context that does not contain a MediaQuery." error in flutter?

The solution to the "MediaQuery.of() called with a context that does not contain a MediaQuery." error that occurs when we want to use MediaQuery on Flutter will be as follows after many attempts.

The widget we will use MediaQuery will not be directly in the main class. Instead, the scaffold or body part will be called from a different class. To give an example;

////////////////////////////   WRONG USAGE /////////////////////////
void main() {
runApp(
runApp(App2());
}
class App2 extends StatelessWidget {

@override
Widget build(BuildContext context) {

return MaterialApp(
theme:
theme: ThemeData(),
home: Scaffold(
body: Container(
color: Colors.pink,
width: MediaQuery.of(context).size.width / 2,
height: MediaQuery.of(context).size.height,
),
color: Colors.pink,
width: MediaQuery.of(context).size.width / 2,
height: MediaQuery.of(context).size.height,
),
),
);
}
}
}
////////////////////////////   CORRECT USAGE /////////////////////////
void main() {
runApp(
runApp(App2());
}
class App2 extends StatelessWidget {

@override
Widget build(BuildContext context) {

return MaterialApp(
theme:
theme: ThemeData(),
home: Scaffold(
body: Home(),
),
);
}
}

class Home extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Container(
color: Colors.pink,
width: MediaQuery.of(context).size.width / 2,
height: MediaQuery.of(context).size.height,
);
}
}

MediaQuery can be used without any problem when the part highlighted with red area above is divided into green area as below. And "MediaQuery.of () called with a context that does not contain a MediaQuery." error will be solved.