iDecode
iDecode

Reputation: 28996

Why snapshot.data returns null in FutureBuilder?

void main() {
  FutureBuilder<bool>(
    future: f(),
    builder: (_, AsyncSnapshot<bool> snapshot) {
      bool data = snapshot.data; // Error
      return Container();
    },
  );
}

Future<bool> f() async => true;

I used bool in all the places and hence my snapshot.data should return a bool too but it returns bool?, why is that so?

Upvotes: 1

Views: 2504

Answers (2)

Bernhard
Bernhard

Reputation: 8851

That is because the signature of data is final T? data, see https://api.flutter.dev/flutter/widgets/AsyncSnapshot/data.html This makes sense, because when your async computation didn't produce a result yet, or an error occcured there is no data to return.

Upvotes: 1

iDecode
iDecode

Reputation: 28996

If you see the implementation of data, it is:

T? get data;

The reason why data has a return type of T? and not T is the error. What if there was an error returned by your Future, in that case you'd receive a null value. You should use it like this:

FutureBuilder<bool>(
  future: f(),
  builder: (_, AsyncSnapshot<bool> snapshot) {
    if (!snapshot.hasError) {
      bool data = snapshot.data!;
    }
    return Container();
  },
)

Upvotes: 2

Related Questions