Home > Net >  Dart/Flutter Firestore Query Doucments to List Problems
Dart/Flutter Firestore Query Doucments to List Problems

Time:12-22

Future<List<CryptoWalletModel>> getUserWalletData(String uuid) async {
    String _dbPath = '${DatabaseGlobals.collectionUsers}/$uuid/${DatabaseGlobals.collectionWallets}';
    Logger.logIt('Wallet path:'   _dbPath);
    final cryptoWalletRef = FirebaseFirestore.instance.collection(_dbPath).withConverter<CryptoWalletModel>(
      fromFirestore: (snapshot, _) => CryptoWalletModel.fromJson(snapshot.data()!),
      toFirestore: (wallet, _) => wallet.toJson(),
    );


    List<CryptoWalletModel> _list = [];

     List<QueryDocumentSnapshot<CryptoWalletModel>> wallets = await cryptoWalletRef
        .get()
        .then((snapshot) => snapshot.docs);
     
    try { //Problem Code Here
      wallets.forEach((element) {
        _list.add(element.data());
      });
     } catch (e) {
        Logger.logIt(e.toString());
    }

    Logger.logIt('BlocWalletRepoListCount: '   wallets.length.toString());
    return _list;
  }

Having a hard time understanding why the for each is skipped over before it is finished. I know that there are five items in wallets but the wallets.forEach string seems not to run.

Any ideas welcomed.

CodePudding user response:

In your code the try block will be executed before the future returned by get() completes. Besides, it is basically not a good idea to mix async / await and .then syntax. Lastly, you can convert the result to list in one step using map.

Try the following code:

try {
  final snapshot = await cryptoWalletRef.get();
  _list = snapshot.docs.map((e) => e.data()).toList();
  return Future.value(_list);
} catch (e) {
  // handler error
}

  • Related