Flutter块等待响应,然后继续

whhtz7ly  于 2023-01-18  发布在  Flutter
关注(0)|答案(4)|浏览(128)

我有以下代码:

class BidBloc extends Bloc<BidEvent, BidState> {
  final FirestoreRepository firestoreRepository;

  BidBloc({required this.firestoreRepository}) : super(BidsLoadingState()) {
    
    on<LoadAllBidsEvent>((event, emit) async {
      emit(BidsLoadingState());
      Item item = event.item;

      Future getBids() async {
        List<Bid> bids = [];

        item.bids?.forEach((element) async {
          Bid? bid = await firestoreRepository.getBidByBidId(bidID: element);
          if (bid != null) {
            DbUser? dbUser = await firestoreRepository.getDBUserByDBUserId(
                dbUserID: bid.bidderID);
            if (dbUser != null) {
              bid.userName = dbUser.userName;
              bids.add(bid);
            }
          }
        });
        return bids;
      }

      List<Bid> bids = await getBids();

      await getBids();

      bids.sort((a, b) => a.timestamp.compareTo(b.timestamp));
      BidsLoadedState(bids);
    });
  }
}

我的bids.sort((a, b) => a.timestamp.compareTo(b.timestamp));在我从我的存储库中检索我的项目之前被触发。因此BidsLoadedState也被空的出价推...
我怎样才能让我的代码在转到下一行之前等待?
谢谢你,

hlswsv35

hlswsv351#

不能将forEach用于async操作,因为它的回调是VoidCallback而不是AsyncCallback,因此无法返回任何值。
有效Dart建议使用for循环代替:

for (final element in item.bids) {
  final bid = await firestoreRepository.getBidByBidId(bidID: element);
}
jq6vz3qz

jq6vz3qz2#

尝试Future for循环,如下所示:

await Future.forEach(item.bids, (element) async{
      Bid? bid = await firestoreRepository.getBidByBidId(bidID: element);
      if (bid != null) {
        DbUser? dbUser = await firestoreRepository.getDBUserByDBUserId(
            dbUserID: bid.bidderID);
        if (dbUser != null) {
          bid.userName = dbUser.userName;
          bids.add(bid);
        }
      }
    });
lkaoscv7

lkaoscv73#

试试这个:

class BidBloc extends Bloc<BidEvent, BidState> {
  final FirestoreRepository firestoreRepository;

  BidBloc({required this.firestoreRepository}) : super(BidsLoadingState()) {

    on<LoadAllBidsEvent>(_LoadBirdEvent);
  }
  
  _LoadBirdEvent(
      LoadAllBidsEvent event,
      Emitter<BidState> emit,
      ) async {
    emit(BidsLoadingState());
    Item item = event.item;

    List<Bid> bids = await getBids();

    bids.sort((a, b) => a.timestamp.compareTo(b.timestamp));
    
    BidsLoadedState(bids);
  }

  Future getBids() async {
    List<Bid> bids = [];

    item.bids?.forEach((element) async {
      Bid? bid = await firestoreRepository.getBidByBidId(bidID: element);
      if (bid != null) {
        DbUser? dbUser = await firestoreRepository.getDBUserByDBUserId(
            dbUserID: bid.bidderID);
        if (dbUser != null) {
          bid.userName = dbUser.userName;
          bids.add(bid);
        }
      }
    });
    return bids;
  }
}
66bbxpm5

66bbxpm54#

我想这就是你要找的。具体来说,这篇文章中Irl的答案dart await on constructor

相关问题