前言
- 最近有時間在研究Flutter開發(fā),從搭建框架(可以參考文章:Flutter基本配置搭建)到開始著手開發(fā)Demo項目,體驗到Flutter開發(fā)的快捷、高效?,F(xiàn)將Flutter開發(fā)中遇到的問題逐步整理出來,供大家參考:
踩坑記錄
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
),
);
}
提煉日志中的一句關(guān)鍵信息:
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、修改了main.dart文件路徑,開啟調(diào)試時項目報錯,提示:

解決方案:提示很明確,需要在flutter的啟動文件里加上
program的value值,value對應(yīng)main.dart的路徑,即:
3、運行項目報錯:Target file "lib\main.dart" not found
解決方案:flutter run --target=xx.dart
4、NotificationListener通知監(jiān)聽滑動事件,通過當前ListView或者ScrollView嵌套了二級ListView或ScrollView,則該通知會監(jiān)聽當前一級和二級所有滾動組件的滑動事件,如果僅想監(jiān)聽一級頁面的滑動事件,則增加depth參數(shù)判斷,代表一級或二級索引值,即:
// 僅監(jiān)聽一級頁面的滑動結(jié)束事件,如果需要監(jiān)聽二級,則將depth判斷值改為1即可
if (notification is ScrollEndNotification && notification.depth == 0) {
// 滑動結(jié)束回調(diào)
print('滑動結(jié)束');
}
5、flutter項目下的iOS目錄,執(zhí)行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項目根目錄,執(zhí)行pod install命令,重新生成與之匹配的Podfile.lock文件即可
6、執(zhí)行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)
.
.
.
解決方案:刪除系統(tǒng)環(huán)境變量之前配置的PUB_HOSTED_URL和FLUTTER_STORAGE_BASE_URL再試
7、本地已安裝好Android Studio和Flutter plugin、Dart plugin,但是執(zhí)行flutter doctor命令的時候依然報錯:

解決方案:終端根目錄下執(zhí)行:
ln -s ~/Library/Application\ Support/Google/AndroidStudio4.1/plugins ~/Library/Application\ Support/AndroidStudio4.1
然后再執(zhí)行flutter doctor即可解決。
8、運行時報錯:_TypeError (type 'String' is not a subtype of type 'Map<String, dynamic>'),報錯截圖如下圖示:

解決方案:接口返回數(shù)據(jù)包一層json.decode:
return response.data;
修改為:
return json.decode(response.data);
Tips:這種錯誤常見于請求第三方接口時觸發(fā),因為返回數(shù)據(jù)沒有經(jīng)過json轉(zhuǎn)化。
9、極光推送在App冷啟動時,點擊推送消息(帶參數(shù)),在iOS設(shè)備上無法正常跳轉(zhuǎn)制定頁面:
解決方案:極光推送插件提供了API用于獲取遠程推送的緩存信息,包含推送必要的參數(shù),獲取參數(shù)之后跳轉(zhuǎn)相應(yīng)頁面即可。
// 獲取極光推送推送冷啟動App時傳參
jPush.getLaunchAppNotification().then((info) {
dynamic extras = getExtras(info);
String? type = extras["type"];
dynamic id = extras["id"];
openPage(type, id);
});
10、數(shù)據(jù)更新發(fā)生在widget構(gòu)建過程中

// 加個延遲即可解決問題
Future.delayed(Duration(milliseconds: 200)).then((value) {
更新數(shù)據(jù)Action-xx;
});
11、頁面是statefulWidget,且在initState里已添加接口請求方法。頁面內(nèi)嵌套進度條組件LinearPercentIndicator。如果切換頁面,發(fā)現(xiàn)頁面沒有實時更新數(shù)據(jù)
解決:

LinearPercentIndicator組件自帶緩存當前頁面狀態(tài)屬性,如若需要調(diào)用initState時實時更新,則將addAutomaticKeepAlive = false即可
12、Flutter頁面加載時間監(jiān)聽
1、在StatefulWidget頁面內(nèi)的initState方法,獲取當前時間的時間戳:DateTime.now().millisecondsSinceEpoch,即為頁面的創(chuàng)建時間。
2、Flutter提供方法,監(jiān)聽頁面的frame繪制回調(diào)完成時間:WidgetsBinding監(jiān)聽方法addPostFrameCallback
3、頁面加載時間 = 頁面繪制完成時間 - 頁面創(chuàng)建時間
print('頁面創(chuàng)建時間為:${DateTime.now().millisecondsSinceEpoch}');
WidgetsBinding.instance!.addPostFrameCallback((timeStamp) {
print('頁面可見時間為:${DateTime.now().millisecondsSinceEpoch}');
});
// 時間戳單位為:毫秒(ms)
// 頁面創(chuàng)建時間為:1658912417399
// 頁面可見時間為:1658912417544
// 頁面加載時間為:1658912417544 - 1658912417399 = 145(ms)= 0.145(s)
一般對于頁面加載時間大于2s,就會有性能問題,需要優(yōu)化。
13、VSCode選擇iPhone 13模擬器,運行時報錯:

解決方案:
進入到下一級ios目錄下,執(zhí)行pod --version,確認本地是否安裝pod:
1、如果有,則代表已安裝,只需要執(zhí)行pod install,然后重啟VSCode即可。
2、如果沒有,則執(zhí)行brew install cocoapods,成功后再執(zhí)行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)
解決方案:緩存導致,重啟開發(fā)者工具,如果還不行,重啟下電腦。