Riyazat Durrani
Riyazat Durrani

Reputation: 668

accessing data from a static function globally

in the init() of my splash screen page, i am calling the function of the next page in order to load the data from backend, and meanwhile the splash screen will run.

the issue here is it only calls the static function, and that function stores the data locally. on my other page, i want data globally, so that i can access that data anywhere on that particular page.

highlights of my code is:

splash screen page init code:

 void initState() {
    super.initState();
    FeedScreen.getdata();
}

and my next page, that is FeedScreen page, where i want data globally is:

class FeedScreen extends StatefulWidget {

  @override
  _FeedScreenState createState() => _FeedScreenState();



  static  void getdata() async{
    CollectionReference collectionReference = FirebaseFirestore.instance
        .collection('Feed');
    var snapshot = await collectionReference.get();
    snapshot.docs.forEach((result){
      collectionReference.doc(result.id).collection('myfeed').snapshots().listen((event) {

        var latarr,longarr,titlearr,descarr,urlarr;

        for(int i=0;i<event.docs.length;i++){
          urlarr.add(event.docs[i].data()['imageurl']);
        
          latarr.add(event.docs[i].data()['lat']);
         
          longarr.add(event.docs[i].data()['long']);
     
          titlearr.add(event.docs[i].data()['title']);
         
          descarr.add(event.docs[i].data()['description']);

        }
      });
    });
  }

i want to access the value of latarr,longarr,titlearr,descarr,urlarr outside the getdata() function.

Upvotes: 0

Views: 180

Answers (2)

Usman Akhlaq
Usman Akhlaq

Reputation: 531

The best and clean approach to do this is that you use State Management. With that, you will be able to manage your variables, etc in your code smoothly and you can access those variables anywhere in your program whenever needed. Some popular ones are Provider , Bloc and GetX.

By using state management you can easily able to Manipulate and access data anywhere in your project.

Upvotes: 0

dm_tr
dm_tr

Reputation: 4763

Declare your variables latarr,longarr,titlearr,descarr,urlarr outside any class. For instance in your main.dart file before the void main() function. These variables will be considered as global variables and will be accessible anywhere in your app.

Upvotes: 1

Related Questions