Search code examples
flutterdartcachingvideo

Downloading and Caching multiple videos before moving to a new screen in Flutter


I have a requirement in a flutter app to play multiple videos in sequence. Basically, one video is played and when I click on a button, the next video should play and so on.

The videos are very short (1-3 seconds) and very small in size. They are stored on Firebase Storage.

The issue is that there can't be any delay in playing the videos. So I am looking for a way to download and cache multiple videos before navigating to the screen that contains the videos.

I have tried using the flutter cache manager like this:

 Future<List<File>> fetchFile(urls) async {

  urls.forEach((url) async {
     var file = await DefaultCacheManager().getSingleFile(url);
     videos.add(file);
   });
   return videos;
} 

Here I try to fetch all the videos from a list of urls and then later I use a Future builder and navigate to the next page with the list of videos.

  Navigator.of(context).push(MaterialPageRoute(builder: (context) => LessonScreen(videos)));

But I've faced a lot of problems with this approach, for example videos not playing in order, or not loading at all, or even crashing the app.

Does anyone know how to achieve this with flutter cache manager or any other approach?

Thanks for the help in advance!


Solution

  • forEach in Dart is async, so you can't predict execution order of iterations, especially if you have async routines inside the block. If you need to guarantee order with internal async calls use a regular for loop.

    for(int i=0;i<urls.length;i++) {
          var file = await DefaultCacheManager().getSingleFile(urls[i]);
          videos.add(file);
        });
    

    This will guarantee videos[] is in the same order as urls[], and that videos[] is populated with File objects before being returned.