前言
- 最近有时间在研究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(
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(
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、修改了main.dart文件路径,开启调试时项目报错,提示:
解决方案:提示很明确,需要在flutter的启动文件里加上
program
的value值,value对应main.dart的路径,即:
3、运行项目报错:Target file "lib\main.dart" not found
解决方案:flutter run --target=xx.dart
4、NotificationListener
通知监听滑动事件,通过当前ListView
或者ScrollView
嵌套了二级ListView
或ScrollView
,则该通知会监听当前一级和二级所有滚动组件的滑动事件,如果仅想监听一级页面的滑动事件,则增加depth
参数判断,代表一级或二级索引值,即:
// 仅监听一级页面的滑动结束事件,如果需要监听二级,则将depth判断值改为1即可
if (notification is ScrollEndNotification && notification.depth == 0) {
// 滑动结束回调
print('滑动结束');
}
5、flutter项目下的iOS目录,执行pod install报错:
[!] ERROR:Parsing unable to continue due to parsing error:
contained in the file located at /Users/xxx/ios/Podfile.lock
解决方案:删除iOS目录下的Podfile.lock文件,cd至ios项目根目录,执行pod install命令,重新生成与之匹配的Podfile.lock文件即可
6、执行flutter upgrade
报错:
Downloading Dart SDK from Flutter engine b793775d2a01e358f7cb3d5eebe2d5e329751b5b...
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
100 201M 100 201M 0 0 1319k 0 0:02:36 0:02:36 --:--:-- 1352k
Building flutter tool...
Because flutter_tools depends on devtools_shared 0.9.7+3 which doesn't match any versions, version solving failed.
Error: Unable to 'pub upgrade' flutter tool. Retrying in five seconds... (9 tries left)
Because flutter_tools depends on devtools_shared 0.9.7+3 which doesn't match any versions, version solving failed.
Error: Unable to 'pub upgrade' flutter tool. Retrying in five seconds... (8 tries left)
.
.
.
解决方案:删除系统环境变量之前配置的PUB_HOSTED_URL
和FLUTTER_STORAGE_BASE_URL
再试
7、本地已安装好Android Studio
和Flutter plugin
、Dart plugin
,但是执行flutter doctor
命令的时候依然报错:
解决方案:终端根目录下执行:
ln -s ~/Library/Application\ Support/Google/AndroidStudio4.1/plugins ~/Library/Application\ Support/AndroidStudio4.1
然后再执行flutter doctor
即可解决。
8、运行时报错:_TypeError (type 'String' is not a subtype of type 'Map')
,报错截图如下图示:
解决方案:接口返回数据包一层json.decode:
return response.data;
修改为:
return json.decode(response.data);
Tips:这种错误常见于请求第三方接口时触发,因为返回数据没有经过json转化。
9、极光推送在App冷启动时,点击推送消息(带参数)
,在iOS设备上无法正常跳转制定页面:
解决方案:极光推送插件提供了API用于获取远程推送的缓存信息,包含推送必要的参数,获取参数之后跳转相应页面即可。
// 获取极光推送推送冷启动App时传参
jPush.getLaunchAppNotification().then((info) {
dynamic extras = getExtras(info);
String? type = extras["type"];
dynamic id = extras["id"];
openPage(type, id);
});
10、数据更新发生在widget构建过程中
// 加个延迟即可解决问题
Future.delayed(Duration(milliseconds: 200)).then((value) {
更新数据Action-xx;
});
11、页面是statefulWidget,且在initState
里已添加接口请求方法。页面内嵌套进度条组件LinearPercentIndicator
。如果切换页面,发现页面没有实时更新数据
解决:
LinearPercentIndicator
组件自带缓存当前页面状态属性,如若需要调用initState
时实时更新,则将addAutomaticKeepAlive = false
即可
12、Flutter页面加载时间监听
1、在StatefulWidget
页面内的initState
方法,获取当前时间的时间戳:DateTime.now().millisecondsSinceEpoch
,即为页面的创建时间。
2、Flutter提供方法,监听页面的frame绘制回调完成时间:WidgetsBinding
监听方法addPostFrameCallback
3、页面加载时间 = 页面绘制完成时间 - 页面创建时间
print('页面创建时间为:${DateTime.now().millisecondsSinceEpoch}');
WidgetsBinding.instance!.addPostFrameCallback((timeStamp) {
print('页面可见时间为:${DateTime.now().millisecondsSinceEpoch}');
});
// 时间戳单位为:毫秒(ms)
// 页面创建时间为:1658912417399
// 页面可见时间为:1658912417544
// 页面加载时间为:1658912417544 - 1658912417399 = 145(ms)= 0.145(s)
一般对于页面加载时间大于2s,就会有性能问题,需要优化。
13、VSCode选择iPhone 13模拟器,运行时报错:
解决方案:
进入到下一级ios
目录下,执行pod --version
,确认本地是否安装pod
:
1、如果有,则代表已安装,只需要执行pod install
,然后重启VSCode即可。
2、如果没有,则执行brew install cocoapods
,成功后再执行pod setup
即可。
14、VSCode运行iOS项目,报错如下:
Launching lib/main.dart on iPhone 14 in debug mode...
main.dart:1
Xcode build done. 91.8s
Error waiting for a debug connection: The log reader failed unexpectedly
Error launching application on iPhone 14.
Exited (sigterm)
解决方案:缓存导致,重启开发者工具,如果还不行,重启下电脑。