flutter
flutter

Reputation: 6786

Where to initialise variable that's needed in initState() in flutter?

I have a the following method:

 getCalendarEventList() async {
    print('here we go agsain');
     await Firestore.instance.collection('availableDates').where('bandId', isEqualTo: identifier).snapshots().listen(
            (data) => data.documents.forEach((doc) => _markedDateMap.add(
            doc['availableDates'].toDate(),
            Event(
                date:doc['availableDates'].toDate(),
                title: 'hello',
                icon: _presentIcon(doc['availableDates'].toDate().day.toString())))));
    setState(() {});
  }

The firebase query contains isEqualTo: identifier as a condition. Identifier is a String which is actually the the Firebase uid of the user. The getCalendarEventList() is called in initState(): Because I want the the calendar to be populated with markers

@override
  void initState() {
    super.initState();
    getCalendarEventList();
  }

I have a method: that gets the firebase uid:

Future<String> inputData() async {
    final FirebaseUser user = await FirebaseAuth.instance.currentUser();
    final String uid = user.uid.toString();
    return uid;
  }

I've put identifier = await inputData(); in the getCalendarEventList() and 9/10 times the markers populate the calendar..(from initState()) So it's a bit 'buggy' ..I think this has to do with calling the uid from Firebase. Where/How should I initialise the variable identifier with the firebase uid?

Upvotes: 0

Views: 49

Answers (1)

Uma
Uma

Reputation: 987

What you can do is call the identifier and then when that's done, you can then call the getCalenderEvents().

   await FirebaseAuth.instance.currentUser().then((user) {
     Firestore.instance.collection('availableDates').where('bandId', isEqualTo: user.uid).snapshots().listen(
            (data) => data.documents.forEach((doc) => _markedDateMap.add(
            doc['availableDates'].toDate(),
            Event(
                date:doc['availableDates'].toDate(),
                title: 'hello',
                icon: _presentIcon(doc['availableDates'].toDate().day.toString())))));
    setState(() {});
    }).catchError((onError){
    handleError();
   });

or

   await FirebaseAuth.instance.currentUser().then((user) {
    setState(() {
    identifier = user.uid;
   });
    getCalenderEvents();
    }).catchError((onError){
    handleError();
   });

Upvotes: 1

Related Questions