I’m having a problem compiling this flutter code. It throws me the following error:
The following assertion was thrown building FutureBuilder(dirty, state: _FutureBuilderState#afa3f):
A build function returned null.
The offending widget is: FutureBuilder
Build functions must never return null.
To return an empty space that causes the building widget to fill available room, return "Container()". To return an empty space that takes as little room as possible, return "Container(width: 0.0, height: 0.0)".
The code is this:
home: Builder(builder: (context) {
return FutureBuilder(
future: DeeplinkConfig().initUniLinks(context),
builder: (_, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return Container(width: 0.0, height: 0.0);
}
return snapshot.data as Widget;
},
);
}),
Please, if someone explains the error and tells me how to fix it, I would greatly appreciate it.
2
Answers
This error message is indicating that the FutureBuilder’s builder callback is returning null as the widget to be displayed.
The builder callback should return a non-null Widget to display in the FutureBuilder. You can either return a widget with dimensions 0.0 width and height, or return a widget indicating that data is loading, like a CircularProgressIndicator.
I would recommend a FutureBuilder that returns a CircularProgressIndicator while the future is waiting:
The issue is this line:
Your Future is out of the waiting state but
data
is still null. You then cast it to aWidget
, which bypasses Dart’s type checking and allows the code to compile but break at runtime.You can assign
snapshot.data
to a local variable and check that it’s not null. That will allow Dart’s type promotion to kick in and you can just return the local variable after the check passes without any cast:This assumes that