flutterasync-awaitflutter-future

Flutter Async Method in initState Not Executing Beyond First Await Call


I'm encountering an issue where a specific line in my asynchronous method isn't executing when called from initState. Here's the method in question:

Future<void> loadNetworkImages() async {
  final currentImages = await _storageService.loadImages(widget.lineup!.id!);
  ref.read(selectedImagesProvider.notifier).state = currentImages.map((image) => image!.url).toList();
}

When I run this, the code execution stops after the await _storageService.loadImages(widget.lineup!.id!) line and the subsequent line to update the state never executes. This method is called within initState of my widget. The rest of the widget builds as expected, but this part just doesn't seem to progress past the await call.

I'm seeking advice on how to correctly handle or debug this situation. Is there a known issue with executing async operations in initState that I'm missing, or is there a better way to ensure the entire method executes as expected?

Thank you for your help!


Solution

  • I am not 100% sure as to what the issue was, but it is quite possible that the query did not return a result which might have resulted in the issue as the function kept waiting for a result.

    Future<void> loadLineupImages(String lineupId) async {
      var imagesSnapshot = await _firestoreService.colRefImages
          .where('lineup_id', isEqualTo: lineupId)
          .get();
    
      final images = imagesSnapshot.docs.map((doc) => ImageItem(
        url: doc['url'] as String,
        label: doc['label'] as String,
        isNew: false,
        id: doc.id
      )).toList();
    
      ref.read(selectedImagesProvider.notifier).state = images;
    
    }
    

    This code ended up working for me.