vol.1 Flutter Coding Dojo

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();
}