flutter 为什么 async 和 await 不起作用?

flutter Why doesn't async and await work?

_getstockList

    _getstockList( List<dynamic> nlist) async {
      Map<String, dynamic> userdocdata;

      var userdata = await  firestore.collection('users').doc('NVPjZEAZneKblrubGZSW').get();
      userdocdata = userdata.data() as Map<String, dynamic>;
      nlist = userdocdata['favorite'];
  }

主要代码

Widget build(BuildContext context) {
    List<dynamic> list = [];
    List<Map<String, dynamic>> stockcardlist = [];
    _getstockList(list);
    print(list);                                           // output
    _getstockInfo(list, stockcardlist);
    

     ~~~
}

_getstockInfo

    _getstockInfo(List<dynamic> nlist, List<Map<String,dynamic>> stockcardlist){

      print(nlist.length);                                // output
    }

想要的结果

print(list)

print(nlist.length) 有效值

但是

结果 print(list) = []

print(nlist.length) = 0

请帮助我使用 Future、sync、unawait 但我无法解决

看起来 _getStockList 没有 return 任何东西。当您传递它时,原始对象不受影响。您可以尝试解决这个问题:

Future<List<dynamic>> _getstockList() async {
      Map<String, dynamic> userdocdata;

      var userdata = await firestore.collection('users').doc('NVPjZEAZneKblrubGZSW').get();
      userdocdata = userdata.data() as Map<String, dynamic>;
      List<dynamic> nlist = userdocdata['favorite'];
      return nlist;
  }

现在你需要调用这个函数来填充列表

Widget build(BuildContext context) {
    List<Map<String, dynamic>> stockcardlist = [];
    List<dynamic> list = await _getstockList(); // DOES NOT WORK!
    print(list);                          
    _getstockInfo(list, stockcardlist);
    
     ...
}

但是,这不起作用,因为不允许在 build 中使用 await,这不是异步的。要解决这个问题,您可以使用 FutureBuilderhttps://api.flutter.dev/flutter/widgets/FutureBuilder-class.html

Widget build(BuildContext context) {
  return FutureBuilder<List<dynamic>>(
    future: _getstockList(),
    builder: (BuildContext context, AsyncSnapshot<List<dynamic>> snapshot) {
      List<dynamic> list = snapshot.data ?? [];

      print(list);
      
      return MyAwesomeScreenWithAList(list);
    }    
  );
}

现在,如果您想在第二个异步函数中使用第一个异步函数的结果,最简单的方法可能是使用两个嵌套的 FutureBuilders。