The instance member 'uid' can't be accessed in an initializer

Viewed 26

Here I have a StreamBuilder with a custom ListView widget.

StreamBuilder<Location>(
            builder: (context, snapshot) {
              if (!snapshot.hasData)
                return CircularProgressIndicator();
              else {
                return ListViewWidget(
                  locations: locationList,                     
                );
              }
            },
        stream: getLocations,
     ),

What I want to do is add the new item to the list and show it in the ListView widget. The problem is, that I can not use the uid and the locationList list because I got this error message:

The instance member 'uid' can't be accessed in an initializer

.

   Stream<Location> getLocations = (() async* {
        await for (var snapshot in FirebaseFirestore.instance
            .collection('loggedin')
            .doc(uid)
            .collection('locations')
            .snapshots()) {
          for (var doc in snapshot.docs) {
            Location location = Location(
                id: doc['id'],
                name: doc['name'],
                description: doc['description'],
             );
            locationList.add(location);    
            yield location;
          }
        }
      })();

How could I update the list and show it on a ListView with StreamBuilder?

1 Answers

I think the problem comes from the way you declared the getLocation stream. It should be declared like a function, this way:

Stream<Location> getLocations() async* {
  // your content here
}

This might correct your error.

But I strongly recommend you reading this link: https://firebase.google.com/docs/firestore/query-data/listen#dart

Which provides a sample of code to get realtime updates from a Firestore collection.

Related