Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter - Error: The getter 'docs' isn't defined for the type 'Object'

I'm working on Flutter 2.2.1 (channel stable). I reccently changed my SDK's environment from 2.7.0 to 2.12.0 (sdk: ">=2.12.0 <3.0.0") in order to add plugins and I got a lot of errors (especially about null safety). One of them is about the extraction of data from firestore (I'm using cloud_firestore: ^2.2.1).

My code:

StreamBuilder(
    stream: FirebaseFirestore.instance
        .collection('towns/${widget.townId}/beacons')
        .orderBy('monument')
        .snapshots(),
    builder: (ctx, snapshot) {
      if (snapshot.connectionState == ConnectionState.waiting)
        return CircularProgressIndicator();
      final beacons = snapshot.data!.docs; // Error here
      return ListView.builder(
          physics:
              NeverScrollableScrollPhysics(),
          shrinkWrap:
              true,
          itemCount: beacons.length,
          itemBuilder: (ctx, index) {
            if (beacons[index]['visibility'] == true) {
              return BeaconCard(
                title: beacons[index]['title'],
                monument: beacons[index]['monument'],
                image: beacons[index]['image'],
                duration: beacons[index]['duration'],
                distance: 0,
                townId: widget.townId,
                uuid: beacons[index]['uuid'],
                fontsizeValue: widget.fontsizeValue,
                languageId: widget.languageId,
              );
            }
            return Container();
          });
    }),

The error is about docs at the line final beacons = snapshot.data!.docs;:

The getter 'docs' isn't defined for the type 'Object'. Try importing the library that defines 'docs', correcting the name to the name of an existing getter, or defining a getter or field named 'docs'.

I'm a new flutter user, I don't understand what to do here. Thanks for your help.

like image 703
Edouard Delep Avatar asked Jun 04 '21 16:06

Edouard Delep


2 Answers

Please provide the expected Stream type. In this case

StreamBuilder<QuerySnapshot>
like image 105
Thiago Carvalho Avatar answered Oct 18 '22 06:10

Thiago Carvalho


You need to declare that the builder snapshot parameter type is AsyncSnapshot.

For example:

StreamBuilder(
        stream: FirebaseFirestore.instance.collection('users').snapshots(),
        builder: (BuildContext context, AsyncSnapshot snapshot) {
          if (snapshot.hasData) {
            List<DocumentSnapshot> docs = snapshot.data!.docs;
            ...
like image 5
genericUser Avatar answered Oct 18 '22 07:10

genericUser