The argument type 'List<dynamic>?' can't be assigned to the parameter type 'List<dynamic>'

Viewed 9260

Currently, I am working on updating the codebase for a Flutter project which was developed on previous versions. The error occurred once we updated to the latest version of Dart and Flutter.

The code here is related to when we are returning the list from the FutureBuilder.

          body: new FutureBuilder<List>(
            future: getData(),
            builder: (context, snapshot) {
              if (snapshot.hasError) print(snapshot.error);

              return snapshot.hasData
                  ? new ItemList(
                      list: snapshot.data, <--- error in here
                    )
                  : new Center(
                      child: new CircularProgressIndicator(),
                    );
            },
          ),

Flutter Version: 2.2.2

Dart Version: 2.13.3

Please help me to point out which part that I should take care of for this one. Thank you!

2 Answers

Your snapshot.data can be null but the ItemList class's list not accept any null value. That’s why you are getting this error.

If you can ensure that, the snapshot.data will always be a non null value then you should use snapshot.data! to avoid this error. But if there is any chance to be the snapshot.data can be null then snapshot.data! will give you another exception. In that case you should use

ItemList(
           list: snapshot.data??[],
         )

This is a bug arising from the new null-safety feature added to Dart.

Depending on how you want to handle null values in ItemList you should either update your code in ItemList to accept null (that is define list as List? list) or update snapshot.data to snapshot.data?? and provide a value for when the snapshot.data is null.

Additional Reading:

  1. You can read more about it here
  2. You can also follow a guide on migrating to null-safety here
Related