theundercoverartist
theundercoverartist

Reputation: 161

The best way to distribute the same FIrestore Data to different Flutter widgets

I need to display different Data from the same Document to different widgets. As of now I start a connection to the Firebase Firestore from each widgets, that needs the data.

So I wondered, if there is a different way of doing this, let's say that I grab the Data when the App opens and then access this Data and don't have to connect to Firestore everytime I need parts of it.

So my question is, is there any way of doing this?

Upvotes: 0

Views: 242

Answers (2)

Celt K. B.
Celt K. B.

Reputation: 789

You could use Inherited Widget. This is what I do in my App using InheritedWidget and BloC:

void main() {

 //Here you get the Data from the Forestore
 final myDataBloc = DataBloc();

 runApp(
     MaterialApp(
      debugShowCheckedModeBanner: false,

     home: MyInheritedWidget(

        //startMyBloc is a variable of the InheritedWidget
        startMyBloc: myDataBloc,
        
        child: AppStarter()),
     ),
 );
}

Now you can acces the data from everywhere with:

MyInheritedWidget.of(context).startMyBloc,

Upvotes: 0

Ørjan
Ørjan

Reputation: 2879

I would recommend taking a look at the "provider" package, which is the recommended way of handling state in a flutter application, even by the flutter team themself.

Here are a detailed description on how to use the provider: https://flutter.dev/docs/development/data-and-backend/state-mgmt/simple

But in short summary, you grab the data once, and all the widgets can access the data from that provider. If you need to listen for changes to the data, you can also provide a listener. Then you just have to update the data once, and all the sub components/widgets will get updated.

Upvotes: 3

Related Questions