skip to Main Content

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


  1. 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:

    return FutureBuilder(
      future: DeeplinkConfig().initUniLinks(context),
      builder: (_, snapshot) {
        if (snapshot.connectionState == ConnectionState.waiting) {
          return CircularProgressIndicator();
        }
        return snapshot.data as Widget;
      },
    );
    
    Login or Signup to reply.
  2. The issue is this line:

    return snapshot.data as Widget;
    

    Your Future is out of the waiting state but data is still null. You then cast it to a Widget, 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:

    return FutureBuilder<Widget>(
      future: DeeplinkConfig().initUniLinks(context),
      builder: (_, snapshot) {
        final data = snapshot.data;
        snapshot.connectionState
        if (snapshot.connectionState == ConnectionState.waiting || data == null) {
          return Container(width: 0.0, height: 0.0);
        }
        return data;
      },
    );
    

    This assumes that

    1. Your future always returns a non-null result when it completes and
    2. That return value is a widget
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search