I have been trying to get the size of the whole context view in Flutter. But every time I try I'm getting the above mentioned error. Here's my code:
import 'package:flutter/material.dart';
void main => runApp(new MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
final size = MediaQuery.of(context).size;
return new MaterialApp(
home: new Scaffold(),
);
}
}
Note: I also tried with a StatefulWidget
.
Please, help me find what I'm doing wrong here.
You need a
MaterialApp
or aWidgetsApp
around your widget. They provide theMediaQuery
. When you call.of(context)
flutter will always look up the widget tree to find the widget.You usually have this in your main.dart:
Add MaterialApp ...
void main() { runApp(MaterialApp( home: HomePage(), )); }
You can access
MediaQuery
when you are insideMaterialApp
. The place where you are accessing the media query is not correct.Please refer below code:
I've purposely created a class
CommonThings
which has static Size so that you can use it throughout the app.Solved by re-run the app(click on stop button in android studio then run again)
There is better way. Above solutions would require you to have only one screen widget or inherit all screens from parent class. But there is solution, place the media query initialization into onGenerateRoute callback function
main.dart
NavigationUtils.dart
WidgetUtils.dart
Warning: It is not copy & paste code, there are some singletons etc. but you should get the point ;)