I’m working with Flutter’s FutureBuilder
and came across a pattern where both snapshot.hasData
and snapshot.data != null
are checked before rendering a widget:
FutureBuilder(
future: future,
builder: (BuildContext context, AsyncSnapshot snapshot) {
if (snapshot.hasData && snapshot.data != null) {
return widgetToBuild;
} else if (snapshot.hasError) {
return Icon(Icons.error_outline);
} else {
return CircularProgressIndicator();
}
}
)
Upon examining the source code of AsyncSnapshot
, I noticed that hasData
is defined as true
if data
is not null
:
bool get hasData => data != null;
Given this implementation, is it redundant to check both snapshot.hasData
and snapshot.data != null
? Wouldn’t snapshot.hasData
suffice since it inherently checks if data
is not null
?
I am curious if there’s a scenario where both checks might be necessary, or if this is just a common misunderstanding in the usage of FutureBuilder
that developers often mistaken.
2
Answers
Yes, it’s redundant, you are right: if you replace the
AsyncSnapshot
code in the first piece you posted, it would look like thisRegarding possible
null
results from afuture
, it happened once in some code of mine (due to an unexpected circumstance), and theFutureBuilder
got stuck on theCircularProgressIndicator
because the data was never detected.So, unless something changed, I think that
null
-returning futures are not to be used withFutureBuilder
.For an easy future handler I’d recommend doing this
And yea, it is redundant casi the hasData getter already does that