felangel / bloc

A predictable state management library that helps implement the BLoC design pattern
https://bloclibrary.dev
MIT License
11.79k stars 3.39k forks source link

Stream a Firestore Collection with the flutter BLoC pattern #355

Closed reignierleo closed 5 years ago

reignierleo commented 5 years ago

Hey Guys, I am completely new in Github, and quite new to Flutter and to the BLoC Pattern. I am working with the flutter_bloc library for Flutter which I find great. However I have a Problem where one of you might be able to help me. As I don't really know how it works here, please tell me if my comment is posted in the wrong place.

So to my Problem: I have built an application based on the BLoC architecture. I want to display a List of names that is stored on Cloud Firestore and when the names are changed on the database I want the name to change in the UI without the User to do anything. Right know, I am sending an event FetchNames() when I click on refresh on the page. But I would like it to refresh automatically when a name changes on cloud firestore. So I want to listen to the cloud firestore collection in which the names are stored. Without using the BLoC pattern I used the StreamBuilder widget and had as Stream a Snapshot of my Data. Now with the Bloc Pattern, when I create in my Repository Layer a Stream, listening to Firestore, how can I connect it to my bloc logic so that an "event" is being send to the Bloc and that the UI reloads each time the firestore database changes. Right know I am using the BlocBuilder widget and the UI is being rebuild each time there is a change in the bloc I provide and I want the rebuild to be done not when an event is coming from the UI but when the data in the database is changing. But as I cannot put a "BlocProvider.of(context) .dispatch(FetchName());" in the repository Layer where my Stream is, what is the alternative. I could build some complex listen function but I am sure there is an easy solution as StreamBuilder.

I hope you can understand my issue and be able to help me. It might be a beginner question but as I am a beginner in App development, please help me anyway :)

Thanks Leo

felangel commented 5 years ago

Hi @reignierleo 👋 Thanks for opening an issue and for giving the bloc library a try!

Regarding your question, I would recommend taking a look at the flutter_bloc_with_stream example application as it shows how you can hook up a bloc to react to changes in a stream. In your case, the repository can just expose a stream that will notify the listener of changes to the dataset in Firestore.

In addition, I am hoping to refactor the todos app to use Firestore in a separate example (#346) so stayed tuned for that 👍

Hope that helps and let me know if you have additional questions!

reignierleo commented 5 years ago

Thanks for your help @felangel :)