Search code examples
flutterdartdart-null-safety

How to get first Future in Futurebuilder using Future.wait with null-safety


I have a Futurebuilder where I call multiple futures. I want to get first future data but I can't find a way to tell null-safety this can't be null.

FutureBuilder(
        future:
            Future.wait([contactInformationController.companiesFuture.value]),
        builder: (context, snapshot) {
          switch (snapshot.connectionState) {
            case ConnectionState.none:
            case ConnectionState.active:
            case ConnectionState.waiting:
              return SizedBox(height: 600, child: LoadingIndicator());
            case ConnectionState.done:
              if (snapshot.hasError) {
                return SizedBox(
                    width: double.infinity,
                    height: 600,
                    child: Center(
                        child: Text("fetcherror".tr,
                            style: Theme.of(context).textTheme.subtitle1!)));
              }

              contactInformationController.companiesData.value = snapshot.data[0]!;

...

It gives me this error:

The method '[]' can't be unconditionally invoked because the receiver can be 'null'.

How can I make this code work with null safety:

contactInformationController.companiesData.value = snapshot.data[0]!;

Solution

  • I fixed it. When using Future.wait. Snapshot returns object data. You need to cast it then call it.

    Like this:

    contactInformationController.companiesData.value = (snapshot.data! as List)[0]