MediaQuery.of() called with a context that does not contain a MediaQuery

報錯截圖:
在這裏插入圖片描述

在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),
      );
  }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章