Flutter future\ async\ await

夫君子之行,静以修身,俭以养德,非淡泊无以明志,非宁静无以至远。——诸葛亮

① async  异步 (规则:能够等待将来或不等待将来,不影响其余人也不受其余人的影响)html

② await  等待  (等待将来;等待能够能是想要的结果或意想不到的结果)git

③ Future 将来  (一种结果)github

 

例如(生活中):

A、男欢女爱的社会(async),多我的在等待(await)本身缘分,缘分这个东西未知数(Future)。服务器

B、一年四季的气候(async),每家每户在等待(await)收货粮食,粮食收成怎样是个未知数(Future)。网络

C、当前商业界如战场(aync),小老板或大老板等待(await)盈利,盈利多少是个未知数(Future)app

...................................................异步

编码思考:

app开发过程当中咱们会用技术和业务逻辑相结合去实现功能。技术只是在逻辑和业务达到用户或者老板的要求后须要经过技术去实现。技术能够更好的控制逻辑实现业务需求。async

示例一:市面上的app首次进入看到可左右滑动的广告页,第二次进入看不得左右滑动的广告页。ide

       判断是首次或者第二次进入APP,本地应该有相应的标志存储(经常使用bool),经过获取的bool值(true\false)就能够更好的控制广告页的显示啦!!!ui

示例二:界面1跳转到界面2,经过界面2返回数据刷新界面1。

        界面1跳转界面2,传递返回数据的标志和要返回的数据,界面1不知道何时界面2会返回数据,可能界面2关闭后返回的数据不是想要的结果(可能为空,可能为想要的结果)。

示例三:网络请求有数据返回时才进行界面的更新。

        当界面触发网络请求时,若是网络断开或者请求的数据为空或服务器异常,都致使界面更新失败。  

示例一

进入应用获取本地变量值,若为null或true,则表示首次进入;若为false则表示第n 次进入app.

class _MyHomePageState extends State<MyHomePage> {
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _isFirst();
  }

  _isFirst() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    bool isFirst = prefs.get("isFirst");
    print("是不是首次进入app_$isFirst");
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          children: <Widget>[
            GestureDetector(
              onTap: () async {
                SharedPreferences prefs = await SharedPreferences.getInstance();
                prefs.setBool("isFirst", true);
              },
              child: Container(
                margin: EdgeInsets.only(top: 20.0),
                child: Padding(
                  child: Text(
                    "模拟首次进入app,存储boolen值为true",
                    style: TextStyle(color: Colors.white),
                  ),
                  padding: EdgeInsets.all(20.0),
                ),
                color: Colors.blue,
              ),
            ),
            GestureDetector(
              onTap: () async {
                _isFirst();
              },
              child: Container(
                  color: Colors.blue,
                  margin: EdgeInsets.only(top: 20.0),
                  child: Padding(
                    child: Text(
                      "模拟第N进入app,存储boolen值为false",
                      style: TextStyle(color: Colors.white),
                    ),
                    padding: EdgeInsets.all(20.0),
                  )),
            ),
          ],
        ),
      ),
    );
  }
}

首次容许+模拟第N次进入2020-07-15 14:55:45.679 30131-30155/com.example.flutter_demo_async I/flutter: 是不是首次进入app_null
2020-07-15 14:56:03.152 30131-30155/com.example.flutter_demo_async I/flutter: 首次进入app_true
2020-07-15 14:56:06.762 30131-30155/com.example.flutter_demo_async I/flutter: 是不是首次进入app_true

 

 怎么没有用到Future???实际上是用到了的,经过查看shared_preferences插件源码,很清楚卡到了(Future、async、await)标示符.

/// Loads and parses the [SharedPreferences] for this app from disk.
  ///
  /// Because this is reading from disk, it shouldn't be awaited in
  /// performance-sensitive blocks.
  static Future<SharedPreferences> getInstance() async {
    if (_completer == null) {
      _completer = Completer<SharedPreferences>();
      try {
        final Map<String, Object> preferencesMap =
            await _getSharedPreferencesMap();
        _completer.complete(SharedPreferences._(preferencesMap));
      } on Exception catch (e) {
        // If there's an error, explicitly return the future with an error.
        // then set the completer to null so we can retry.
        _completer.completeError(e);
        final Future<SharedPreferences> sharedPrefsFuture = _completer.future;
        _completer = null;
        return sharedPrefsFuture;
      }
    }
    return _completer.future;
  }

假如咱们只使用async和await来实现返回没有Future的自定义方法,结果会怎么样呢????

@override
  void initState() {
    // TODO: implement initState
    super.initState();
    bool isFirst = _isFirst();
    print("是不是首次进入app_$isFirst");
  }

  _isFirst() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    bool isFirst = prefs.getBool("isFirst");
    return isFirst;
  }

运行就报错啦:

I/flutter (30467): ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
I/flutter (30467): The following assertion was thrown building Builder: 
I/flutter (30467): type 'Future<dynamic>' is not a subtype of type 'bool'
I/flutter (30467):                                                      
I/flutter (30467): Either the assertion indicates an error in the framework itself, or we should provide substantially
I/flutter (30467): more information in this error message to help you determine and fix the underlying cause.
I/flutter (30467): In either case, please report this assertion by filing a bug on GitHub:
I/flutter (30467):   https://github.com/flutter/flutter/issues/new?template=BUG.md

type 'Future<dynamic>' is not a subtype of type 'bool' ,当咱们返回用await标示的返回结果默认返回Future<dynamic>,因此咱们须要配合Future+要返回的数据类型(int\bool\String\double\float.........)

async+future+await+要返回的数据类型(int\bool\String\double\Float...............)

@override
  void initState(){
    // TODO: implement initState
    super.initState();
    _init();
  }

  _init() async{
    bool isFirst =await _isFirst();
    print("是不是首次进入app_$isFirst");
  }


  Future<bool> _isFirst() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    bool isFirst = prefs.getBool("isFirst");
    return isFirst;
  }

运行结果:
I/flutter (30747): 是不是N次进入app_true
I/flutter (30747): 首次进入app_true
I/flutter (30747): 是不是N次进入app_true
I/flutter (30747): 首次进入app_true
I/flutter (30747): 是不是N次进入app_true

flutter_demo_async工程

参考: 

https://dart.dev/codelabs/async-await

Future:https://book.flutterchina.club/chapter1/dart.html?h=Future

await:https://book.flutterchina.club/chapter1/dart.html?q=await

async:https://book.flutterchina.club/chapter2/flutter_assets_mgr.html?h=async