Reputation: 113
Also getting
Try making the call condtional (using ?.) or adding a null check to the target
for the same line(s):
Text("${snapshot.data[index]}")
If I do that I get only the error message from the title.
I have actually copy/pasted a FutureBuilder from another project of mine where it is working perfectly fine but in this one I get this error. The only difference is that in the not working project I see this:
AsyncSnapshot<Object?>
and in the working project I see this:
AsyncSnapshot<dynamic>
If I hover over snapshot
The entire section looks like this:
FutureBuilder(
future: http_functions.myAsyncFunction(),
builder: (context, snapshot) {
return snapshot.hasData
? Scrollbar(
controller: _scrollController,
isAlwaysShown: true,
thickness: 4,
child: ListView.builder(
physics: const AlwaysScrollableScrollPhysics(),
shrinkWrap: true,
controller: _scrollController,
itemCount: 10,
itemBuilder: (context, index) {
return Card(
child: ListTile(
title: Text("${snapshot.data[index]}"),
),
);
},
),
)
: const CircularProgressIndicator();
},
)
While myAsyncFunction()
returns a List<dynamic>
using return json.decode(response.body);
Upvotes: 1
Views: 694
Reputation: 5060
Use snapshot.data?.docs?[0].data()
. It will return the value if not null and return null otherwise.
Upvotes: 0
Reputation: 161
In AsyncSnapshot<Object?>
the object is nullable which means it can have a value or can be null. Now you are accessing the object like snapshot.data[index]
. Here the snapshot.data
can be null and accessing index of a null array can cause error.
So in order to access your array safely replace snapshot.data[index]
with snapshot.data?[index] ?? ''
or you can use the null assertion operator like this if you are sure that your list can't be null snapshot.data![index]
.
Upvotes: 0
Reputation: 2757
You need to define the type parameter of the FutureBuilder. And cast the snapshot.data to not null by using the !
operator
FutureBuilder<List<dynamic>>(
future: http_functions.myAsyncFunction(),
builder: (context, snapshot) {
return snapshot.hasData
? Scrollbar(
controller: _scrollController,
isAlwaysShown: true,
thickness: 4,
child: ListView.builder(
physics: const AlwaysScrollableScrollPhysics(),
shrinkWrap: true,
controller: _scrollController,
itemCount: 10,
itemBuilder: (context, index) {
return Card(
child: ListTile(
title: Text("${snapshot.data![index]}"),
),
);
},
),
)
: const CircularProgressIndicator();
},
)
Upvotes: 3