Why snapshot.data returns null in FutureBuilder?

Issue

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?

Solution

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();
  },
)

Answered By – iDecode

Answer Checked By – David Marino (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *