Home > Software engineering >  The body might complete normally, causing 'null' to be returned, but the return type, 
The body might complete normally, causing 'null' to be returned, but the return type, 

Time:04-22

I have this error in my code before the { (builde:(context,snapshot)

buildSearchresult() {
    return FutureBuilder(
        future: searchresultfuture,
        builder: (context, snapshot) {
          if (!snapshot.hasData) {
            return CircularProgress();
          }
          
          
        });
  }

CodePudding user response:

The builder must always return a widget. However, in your code, if the condition !snapshot.hasData is not satisfied, the builder returns null. So you should return a widget outside this condition:

buildSearchresult() {
    return FutureBuilder(
        future: searchresultfuture,
        builder: (context, snapshot) {
          if (!snapshot.hasData) {
            return CircularProgress();
          }
          return Container(); // The widget containing your data
        });
  }

CodePudding user response:

Possible duplicate.

You are returning widget only when you don't have data. you need to return widget on every possible case, like

  • error
  • on data
  • no data
  • waiting

You can also simplify by returning default widget others state.

builder: (context, snapshot) {
  if (snapshot.connectionState == ConnectionState.waiting) {
 /// return your widget while loadling
 } else if (snapshot.hasError) { 
 /// return your widget based on error
  } else if (snapshot.hasData) {
 /// return your widget while have data
  } else if (!snapshot.hasData) {
 /// return your widget while there is no data
  } else {
 /// return  widget
  }
},

CodePudding user response:

You forgot return from your FutureBuilder(). The return you have is just for your if statement not FutureBuilder().

Use:

buildSearchresult() {
    return FutureBuilder(
        future: searchresultfuture,
        builder: (context, snapshot) {
          if (!snapshot.hasData) {
            return CircularProgress();
          }
          return ...     // add this to return something.
          
        });
  }

See a similar question here for more info.

  • Related