美文网首页
Flutter async await listen的赋值问题

Flutter async await listen的赋值问题

作者: 你妹妹的灵魂 | 来源:发表于2020-02-20 17:53 被阅读0次

    在学习Flutter的过程中,你肯定也被async await 和 listen,这几个玩意儿折腾的吐血过。长篇大论没有,说最基本的赋值问题:

    async在取值的时候,一般会使用:.then 或者在ui层面使用FutureBuilder组件:

    比如:.then

    Future<List> installedAppsList() async {
      List installedApps;
      await Process.start('ls', ["-m", "/Applications"]).then((Process process){
        process.stdout.transform(utf8.decoder).listen((data) {
          installedApps = data.split(', ');
          installedApps =installedApps;
          print (installedApps);
        });
      });
      return installedApps;
    }
    

    比如:FutureBuilder

    FutureBuilder(
          builder: (context, snapshot) {
            switch (snapshot.connectionState) {
              case ConnectionState.none:
              case ConnectionState.active:
              case ConnectionState.waiting:
                print('waiting');
                return Center(child: CupertinoActivityIndicator());
              case ConnectionState.done:
                print('done');
                if (snapshot.hasError) {
                  return Center(
                    child: Text('网络请求出错'),
                  );}
                return generateListView(); }
            return null; },
          future: _future,
        ),
    

    在同步的数据赋值时,我们一般这样写:
    String data;
    data = getData();

    而使用异步直接赋值的做法应该是:

    String data;
    setData() async {
      data = await getData();    //getData()延迟执行后赋值给data
    }
    

    明白以上三种方法,基本上就解决了异步赋值的主要问题。

    再说listen,同样第一个代码段里面,

    process.stdout.transform(utf8.decoder).listen((data) {
          var appVersion = json.decode(data)['CFBundleShortVersionString'];
          return (appVersion); 
        });
    

    我想直接赋值怎么办?
    用 join:

    Future<List> installedAppsList() async {
      Process process = await Process.start('ls', ["-m", "/Applications"]);
      var result = process.stdout.transform(utf8.decoder).join;
      return result;
    }
    

    相关文章

      网友评论

          本文标题:Flutter async await listen的赋值问题

          本文链接:https://www.haomeiwen.com/subject/eqzxqhtx.html