初见

Flutter开发 踩坑记录

2020-04-26  本文已影响0人  Smalla
前言
踩坑记录

1、先看错误日志:

flutter: ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
flutter: The following assertion was thrown building MyApp(state: _BottomNavigationBarState#ccb0e):
flutter: MediaQuery.of() called with a context that does not contain a MediaQuery.
flutter: No MediaQuery ancestor could be found starting from the context that was passed to MediaQuery.of().
flutter: This can happen because you do not have a WidgetsApp or MaterialApp widget (those widgets introduce
flutter: a MediaQuery), or it can happen if the context you use comes from a widget above those widgets.
flutter: The context used was:
flutter:   Scaffold
flutter:
flutter: The relevant error-causing widget was:
flutter:   MyApp 
lib/…/Base/main.dart:7
flutter:
flutter: When the exception was thrown, this was the stack:

问题代码 :

@override
  Widget build(BuildContext context) {
    return Scaffold(
      body: _bottomNavPages[_selectedIndex],
      bottomNavigationBar: BottomNavigationBar(
        items: <BottomNavigationBarItem>[
          BottomNavigationBarItem(
              title: Text("tab1"),
              icon:Image.asset("normal.png")),
          BottomNavigationBarItem(
              title: Text("tab2"),
              icon: Image.asset("normal.png")),
          BottomNavigationBarItem(
              title: Text("tab3"),
              icon: Image.asset("normal.png")),
          BottomNavigationBarItem(
              title: Text("tab4"),
              icon:Image.asset("normal.png")),
        ],
        backgroundColor: Colors.white,
        currentIndex: _selectedIndex,
        unselectedItemColor: Colors.grey,
        selectedItemColor: Colors.orange
      ),
    );
  }

提炼日志中的一句关键信息:
This can happen because you do not have a WidgetsApp or MaterialApp widget XXX
这里是布局底部四个Tabbar,是一个Material组件,所以用Scaffold包裹,这里就会报错,需要用MaterialApp再包裹一层,解决如下:

@override
  Widget build(BuildContext context) {
    return MaterialApp(
       home: Scaffold(
       body: _bottomNavPages[_selectedIndex],
       bottomNavigationBar: BottomNavigationBar(
       items: <BottomNavigationBarItem>[
          BottomNavigationBarItem(
              title: Text("tab1"),
              icon:Image.asset("normal.png")),
          BottomNavigationBarItem(
              title: Text("tab2"),
              icon: Image.asset("normal.png")),
          BottomNavigationBarItem(
              title: Text("tab3"),
              icon: Image.asset("normal.png")),
          BottomNavigationBarItem(
              title: Text("tab4"),
              icon:Image.asset("normal.png")),
        ],
        backgroundColor: Colors.white,
        currentIndex: _selectedIndex,
        unselectedItemColor: Colors.grey,
        selectedItemColor: Colors.orange
       ),
      ),
    );
  }

2、

上一篇 下一篇

猜你喜欢

热点阅读