前言
- 最近有時間在研究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、修改了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<String, dynamic>')
,報錯截圖如下圖示:
解決方案:接口返回數據包一層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)
解決方案:緩存導致,重啟開發者工具,如果還不行,重啟下電腦。