Ted Henry
Ted Henry

Reputation: 1492

Flutter FutureBuilder hasData and connectionState

The article Fetch data from the internet shows the following snippet of code for FutureBuilder to process the snapshot.

FutureBuilder<Post>(
  future: post,
  builder: (context, snapshot) {
    if (snapshot.hasData) {
      return Text(snapshot.data.title);
    } else if (snapshot.hasError) {
      return Text("${snapshot.error}");
    }

    // By default, show a loading spinner.
    return CircularProgressIndicator();
  },
);

This just doesn't seem quite solid enough. Couldn't there be cases when snapshot.connectionState is ConnectionState.done but both snapshot.hasData and snapshot.hasError are both false? A future can legitimately return null as its result. The snippet above would then incorrectly show the loading indicator indefinitely, wouldn't it?

Upvotes: 4

Views: 2561

Answers (1)

orimdominic
orimdominic

Reputation: 1135

According to the documentation, snapshot.hasData

Returns whether this snapshot contains a non-null data value.

This can be false even when the asynchronous computation has completed successfully, if the computation did not return a non-null value. For example, a Future will complete with the null value even if it completes successfully.

Thus, snapshot.hasData will return false on null value reception, confirming your thoughts in your question.

snapshot.hasError

Returns whether this snapshot contains a non-null error value.

This is always true if the asynchronous computation's last result was failure.

A non-null error value is gotten when the server responds with a status that indicates a failure such a 404, 500 with an error object accompanying the snapshot or whatever is returned from the operation

snapshot.hasError will be false on a failed request or a case where the request was never even made (in the case of no network or poor network) and the response has a non-null value (there will be an error object attached to the snapshot on ConnectionState.DONE being true; i.e on completion),

snapshot.hasData being false means that ConnectionState.DONE is true and snapshot.hasData is null (including cases where the expected result of the operation is of type void)

The answer to your question depends on whether an error object was attached to the response from the server or not when the request is erroneous because of something that occurred on the server side. There'll always be an error object attached to the response if the request failed because it was never made because of bad network.

If the error object is null, then the LoadingIndicator will display indefinitely

Upvotes: 3

Related Questions