The getter 'length' isn't defined for the type 'Object'

Viewed 4576

I get the following error "The getter 'length' isn't defined for the type 'Object'" when checking the length of snapshot.data in the itemCount property of a listViewBuilder:

child: StreamBuilder(
       stream:_firestoreService?.getProducts(), 
             builder: (context, snapshot) {
                   if (!snapshot.hasData) {
                          return CircularProgressIndicator();
                   } else {
                          return ListView.builder(
                                 itemExtent: 80,
                                 itemCount: snapshot.data!.length,
                                 itemBuilder: (context, index) {

The data is coming from firestore

3 Answers

I think the change you need to make is on this line builder: (context, snapshot)

When you use that signature, the type that snapshot is assigned is AsyncSnapshot<Object?> , which does not have the length getter defined on it.

However, if you modify the builder line to be builder: (context, AsyncSnapshot snapshot), then you'll get the length getter on snapshot.data. Use it as snapshot.data!.length.

To sum it up, i think this is what it should be:

child: StreamBuilder(
       stream:_firestoreService?.getProducts(), 
             builder: (context, AsyncSnapshot snapshot) {
                   if (!snapshot.hasData) {
                          return CircularProgressIndicator();
                   } else {
                          return ListView.builder(
                                 itemExtent: 80,
                                 itemCount: snapshot.data!.length,
                                 itemBuilder: (context, index) {

using AsyncSnapshot snapshot instead of using just snapshot in the code.

That is using

builder: (context, AsyncSnapshot snapshot) {}

instead of

builder: (context, snapshot) {}

It worked 10000% for me.

In the latest versions of the cloud_firestore plugin, you need to indicate the type of your query, before you can get the data from it. I recommend checking out the documentation on migrating to version 2.0, which shows that this typically will look something like changing

Query query

To

Query<Map<String, dynamic>> query

The exact code you need to change depends on your implementation, and isn't clear from what you shared, but it'll be some type of type annotation like shown above (and in the docs I linked).

Related