前言
- 最近有时间在研究Flutter开发,从搭建框架(可以参考文章:Flutter基本配置搭建)到开始着手开发Demo项目,体验到Flutter开发的快捷、高效。现将Flutter开发中遇到的问题逐步整理出来,供大家参考:
踩坑记录
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、
网友评论