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.
The
AsyncSnapshot#hasData()comes from commit fbd4bb9.There was a large debate around that in issue 34545:
I suspect this is why you see code like:
But in the current state, it is still redundant.