skip to Main Content

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


  1. Yes, it’s redundant, you are right: if you replace the AsyncSnapshot code in the first piece you posted, it would look like this

    if (snapshot.data != null && snapshot.data != null) {
    

    Regarding possible null results from a future, it happened once in some code of mine (due to an unexpected circumstance), and the FutureBuilder got stuck on the CircularProgressIndicator because the data was never detected.
    So, unless something changed, I think that null-returning futures are not to be used with FutureBuilder.

    Login or Signup to reply.
  2. For an easy future handler I’d recommend doing this

    And yea, it is redundant casi the hasData getter already does that

    FutureBuilder(
      future: getValue(),
      builder: (BuildContext context, AsyncSnapshot snapshot) {
        // Check if is loading
        if (snapshot.connectionState == ConnectionState.waiting) {
          return const CircularProgressIndicator();
        }
    
        // When the builder has data
        if (snapshot.hasData) {
          // Here you can force no null without issues
          return Text(snapshot.data);
        }
    
        return const Icon(Icons.error_outline);
      },
    )
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search