Home > Enterprise >  flutter Why doesn't async and await work?
flutter Why doesn't async and await work?

Time:05-04

_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'];
  }

Main Code

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
    }

Desired result

print(list)

print(nlist.length) valid value

BUT

result print(list) = []

print(nlist.length) = 0

please help me i use Future, sync, unawait but i cant solve

CodePudding user response:

It looks like _getStockList doesn't return anything. When you pass it, the original object remains unaffected. You could try to fix that:

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

Now you need to call this function to fill the list

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

However, this does not work, since you are not allowed to use await in build, which is not async. To get around this, you can use a FutureBuilder: https://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);
    }    
  );
}

Now if you want to use the results of the first async function in a second one, the easiest will probably be, though not ideal, to use two nested FutureBuilders.

  • Related