Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter with Firestore: StreamBuilder vs StreamProvider

I’m developing an app with Flutter, and I’m using Cloud Firestore. Is there any reason to prefer one between StreamBuilder and StreamProvider?

like image 721
Marco Avatar asked Jan 14 '20 15:01

Marco


People also ask

What is the difference between StreamBuilder and StreamProvider?

Use StreamBuilder for a stream that you are sure you will only need at that same widget. Use StreamProvider if your app is growing, passing this stream data through your app widgets will get messy.

When should I use StreamBuilder flutter?

StreamBuilder is a widget that builds itself based on the latest snapshot of interaction with a stream. This is mainly used in applications like chat application clock applications where the widget needs to rebuild itself to show the current snapshot of data.

What does StreamBuilder do in flutter?

The StreamBuilder can listen to exposed streams and return widgets and catch snapshots of got stream information. The stream builder takes two contentions. The Stream resembles a line. At the point when you enter a value from one side and a listener from the opposite side, the listener will get that value.


1 Answers

Is there any reason to prefer one?

StreamBuilder is nice and easy to use for a stream that you are sure you will only need at that same widget. If your app is growing, passing this stream data through your app widgets will get messy, in that case, use StreamProvider.

Why?

StreamProvider is a more complete solution than StreamBuilder:

  • StreamBuilder is a widget that comes with Flutter, and rebuilds itself every time the stream gets updated, that's it's only job.
  • StreamProvider is a widget that comes with the Provider package, it's built using StreamBuilder, but combines this with InheritedWidget, allowing you to pass information through the tree of widgets efficiently.

Some useful info and code

David King explains in this video an evolution from using StreamBuilder to StreamProvider, explaining their benefits (and MultiProvider, which allows to have multiple streams). His code is in this GitHub repo.

In this Fireship article, there's a video and code explaining how to use Firebase with Provider. There's a very useful example on using it with Firebase user authentication.

like image 113
Rafael Díaz Avatar answered Oct 01 '22 13:10

Rafael Díaz