報錯截圖:
在stack overflow上找到答案:
You need a MaterialApp or a WidgetsApp around your widget. They provide the MediaQuery. When you call .of(context) flutter will always look up the widget tree to find the widget
return 的時候加上 MaterialApp
錯誤代碼:
Widget _widgetForRoute(String route) {
switch (route) {
case 'route1':
return Scaffold(
appBar: AppBar(
title: Text('Flutter頁面'),
),
body: Center(
child: Text('Flutter頁面,route=$route'),
),
);
default:
return Center(
child: Text('Unknown route: $route', textDirection: TextDirection.ltr),
);
}
}
正確代碼:
Widget _widgetForRoute(String route) {
switch (route) {
case 'route1':
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Flutter頁面'),
),
body: Center(
child: Text('Flutter頁面,route=$route'),
),
),
);
default:
return Center(
child: Text('Unknown route: $route', textDirection: TextDirection.ltr),
);
}
}