rozerro
rozerro

Reputation: 7196

The getter 'length' was called on snapshot's data

When the app starts it throws an Exception caught by widgets library in a console:

======== Exception caught by widgets library ======================================================= The following NoSuchMethodError was thrown building
StreamBuilder<List<Entry>>(dirty, state:
_StreamBuilderBaseState<List<Entry>, AsyncSnapshot<List<Entry>>>#97504): The getter 'length' was called on
null. Receiver: null Tried calling: length on `itemCount: snapshot.data.length`, 

But the whole app nonetheless works in emulator. What is the reason of that?

StreamBuilder<List<Entry>>(
          stream: entryProvider.entries,
          builder: (context, snapshot) {
            return ListView.builder(
                itemCount: snapshot.data.length, // the error is here
                itemBuilder: (context, index) { ...

Upvotes: 0

Views: 2414

Answers (3)

MhdBasilE
MhdBasilE

Reputation: 458

 solved the problem by replacing StreamBuilder<Object> with StreamBuilder<QuerySnapshot>. by default the StreamBuilder comes in this form StreamBuilder<Object>

this will work 100%

Upvotes: 0

Aniket Kharpatil
Aniket Kharpatil

Reputation: 11

Use snapshot.data.size instead of .length.

Upvotes: 0

ASAD HAMEED
ASAD HAMEED

Reputation: 2900

When the stream is busy loading data, snapshot.data will be null until the ConnectionState of StreamBuilder is ConnectionState.done.

There are a few fixes you can try.

1. Use if (snapshot.hasData)

This will ensure that snapshot.data is used only when it is not null

2. Use Null operator

When trying to get the length of snapshot.data, try this

    snapshot?.data.length ?? 0

3. Check ConnectionState

You can also check the ConnectionState of StreamBuilder but you might still need to use the first solution i.e, snapshot.hasData, normally I would prefer one of the above solutions.

Upvotes: 3

Related Questions