Dart/Flutter Firestore 查询文档以列出问题

Dart/Flutter Firestore Query Doucments to List Problems

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

很难理解为什么 for each 在完成之前就被跳过了。我知道钱包里有五件物品,但 wallets.forEach 字符串似乎不是 运行.

欢迎提出任何想法。

在您的代码中,try 块将在 get() 返回的未来完成之前执行。此外,混用 async / await.then 语法基本上不是一个好主意。最后,您可以使用 map.

一步将结果转换为列表

试试下面的代码:

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