Caching images from Stream response in Flutter from Firebase

31 views Asked by At

In my flutter application with firebase database, I am using stream response to get data from firebase firestore. Following is code of fetching

Stream<List<PostEntity>> readPosts(PostEntity post) {
    final postCollection = firebaseFirestore
        .collection(FirebaseConstants.posts)
        .orderBy("createAt", descending: true);
    return postCollection.snapshots().map((querySnapshot) =>
        querySnapshot.docs.map((e) => PostModel.fromSnapshot(e)).toList());
  }

Then I am converting stream response to list of posts.

Future<void> readPosts({ required PostEntity post})async{
    emit(PostLoading());
    try {
      final streamResponse = readPostsUsecase.call(post);
      streamResponse.listen((posts) {
        emit(PostLoaded(posts: posts));
      });
    }on SocketException catch (_) {
      emit(PostFailure());
    }
    catch (_) {
      emit(PostFailure());
    }
  }

It is returning Posts data containing link to Posturl, which is also stored in Firebase Storage. I am using "cached_network_image" to cache images, but it starts loading after I scroll, means caching is not working properly. Though when I turn off the internet, Cached images already gets load, but why they starts loading when internet is on. Here I am displaying image:

return CachedNetworkImage(
          imageUrl: photoUrl,
          fit: BoxFit.cover,
          progressIndicatorBuilder: (context, url, progress) {
            return Center(
              child: CircularProgressIndicator(
                value: progress.progress,
              ),
            );
          },
          errorWidget: (context, url, progress) {
            return Image.asset(
              "assets/images/default-user.png",
              fit: BoxFit.cover,
            );
          },
        );  

I want these images to be properly cached and after loading first time they should not load every other time. How do i do it?

0

There are 0 answers