Flutter 開發者的道場,練習基本招式。精選 Stack Overflow 網站 flutter、dart 標籤下的常見問題,總結爲實用、簡短的招式。設計模式
Flutter 發佈以來,受到愈來愈多的開發者和組織關注和使用。快速上手開發,須要瞭解 Dart 語言特性、Flutter 框架 SDK 及 API、慣用法、異常處理、輔助開發的工具使用等...。bash
隱藏調試模式橫幅。app
return MaterialApp( title: 'Flutter Demo', debugShowCheckedModeBanner: false, theme: ThemeData( primarySwatch: Colors.blue, ), home: MyHomePage(title: 'Flutter Demo Home Page'), );
打印日誌調試應用。框架
import 'package:flutter/foundation.dart'; print('logs'); debugPrint('logs');
當日志輸出過多時,Android 系統可能會丟棄一些日誌行,爲了不這種狀況使用 Flutter foundation 庫提供的 debugPrint()
方法。ide
指定 App 用戶界面能夠顯示的方向集[...]。函數
SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp]);
獲取手機屏幕寬高。工具
double width = MediaQuery.of(context).size.width; double height = MediaQuery.of(context).size.height;
獲取 App 能夠顯示的矩形邊界,排除被系統 UI(狀態欄)或硬件凹槽遮擋部分。網站
EdgeInsets devicePadding = MediaQuery.of(context).padding;
添加、顯示圖片資源。ui
Image.asset('images/cat.png')
確保在 pubspec.yaml
文件中顯式標識資源路徑,不然將會拋出異常。this
flutter: assets: - images/cat.png
flutter: ══╡ EXCEPTION CAUGHT BY IMAGE RESOURCE SERVICE ╞══ flutter: The following assertion was thrown resolving an image codec: flutter: Unable to load asset: assets/heart_icon.png
注意:在 .yaml 類型的文件中,正確的空格縮進相當重要。
導航到新頁面(Route)而後返回。
Navigator.push(context, MaterialPageRoute(builder: (BuildContext context) => MyPage());
Navigator.pop(context);
使用自定義 Widget 替換紅屏 ErrorWidget。
ErrorWidget.builder = (FlutterErrorDetails details) { return Container(); }
確保 setState() 方法不會在 dispose() 方法以後調用。
if (this.mounted){ setState((){ //Your state change code goes here }); }
setState() 方法可能會拋出異常:
throw FlutterError( 'setState() called after dispose(): $this\n' 'This error happens if you call setState() on a State object for a widget that ' 'no longer appears in the widget tree (e.g., whose parent widget no longer ' 'includes the widget in its build). This error can occur when code calls ' 'setState() from a timer or an animation callback. The preferred solution is ' 'to cancel the timer or stop listening to the animation in the dispose() ' 'callback. Another solution is to check the "mounted" property of this ' 'object before calling setState() to ensure the object is still in the ' 'tree.\n' 'This error might indicate a memory leak if setState() is being called ' 'because another object is retaining a reference to this State object ' 'after it has been removed from the tree. To avoid memory leaks, ' 'consider breaking the reference to this object during dispose().' );
Dart 單例設計模式,使用工廠構造函數。
class Singleton { static final Singleton _singleton = Singleton._internal(); factory Singleton() { return _singleton; } Singleton._internal(); }