'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.
Solution 1:[1]
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;
...
Solution 2:[2]
body: FutureBuilder( future: usersref.get() , builder:(context, snapshot){
if(snapshot.hasData){
return ListView.builder(
itemCount:snapshot.data!.docs.length, //here error
itemBuilder: (context,i){
return Text("");
});
}
if(snapshot.hasError){
}
else{
return Text("LOADING . . . .")
}
})
Solution 3:[3]
Only type
AsyncSnapshot
in builder argument of streamBuilder with snapshot. Like this
StreamBuilder(
stream: *Your Code*
,
builder: (ctx, AsyncSnapshot snapshot) {
*Your Code*
}
)
Solution 4:[4]
Please let flutter know the snapshot type inside the builder:
builder: (ctx, AsyncSnapshot<QuerySnapshot> snapshot)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | genericUser |
| Solution 2 | idris Zz |
| Solution 3 | Mohammad Bilal Akbar |
| Solution 4 | Obada Al Ahdab |
