Search code examples
firebaseflutterdartgoogle-cloud-firestoreglobal-variables

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.


Solution

  • 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.