apowerfulman 2019-07-01
Flutter 开发者的道场,练习基本招式。精选 Stack Overflow 网站 flutter、dart 标签下的常见问题,总结为实用、简短的招式。
Flutter 发布以来,受到越来越多的开发者和组织关注和使用。快速上手开发,需要了解 Dart 语言特性、Flutter 框架 SDK 及 API、惯用法、异常处理、辅助开发的工具使用等...。
隐藏调试模式横幅。
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()
方法。
指定 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;
添加、显示图片资源。
Image.asset('images/cat.png')
确保在 pubspec.yaml
文件中显式标识资源路径,否则将会抛出异常。
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(); }