Search code examples
flutterdartdart-null-safety

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


I am using a FutureBuilder with two downloads and putting each index to a list to load/show them in my app. With null safety there is an error:

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

Try making the call conditional (using '?.') or adding a null check to the target ('!').

How can i solve this error in the snapshot (snapshot.data[0])? Thanks for help.

enter image description here

          FutureBuilder(
            future: Future.wait([downloadsuche(), downloadsuchvorschlag()]),
            builder: (context, snapshot) {
              if (snapshot.hasData) {
                //List<AdressSuche> adresse = snapshot.data;

                List<AdressSuche> adresse = snapshot.data[0];
                List<AdressSuche> sv1 = snapshot.data[1];

                return IconButton(
                  icon: const Icon(Icons.search),
                  onPressed: () {
                    showSearch(context: context, delegate: DataSearch(adresse, sv1));
                  },
                );
              } else if (snapshot.hasError) {
                return IconButton(icon: const Icon(Icons.search), onPressed: () {});
                //return RefreshIndicator(onRefresh: _refreshdata, child: Center(child: CircularProgressIndicator()));
              }
              return IconButton(icon: const Icon(Icons.search), onPressed: () {});
            },
          ),

Solution

  • Replace

    List<AdressSuche> adresse = snapshot.data[0];
    List<AdressSuche> sv1 = snapshot.data[1];
    

    with

    var adresse = (snapshot.data as List)[0] as List<AdressSuche>;
    var sv1 = (snapshot.data as List)[1] as List<AdressSuche>;