0

I try to make flutter null safety migration, I have this code working before and now I have this error on List(10)

The default 'List' constructor isn't available when null safety is enabled. Try using a list literal, 'List.filled' or 'List.generate'

Here is my code

 List<CardModel> createCards() {
        List<String> asset = [];
        List(10).forEach((f) => asset.add('0${(asset.length + 1)}.png'));
        List(10).forEach((f) => asset.add('0${(asset.length - 10 + 1)}.png'));
        return List(20).map((f) {
          int index = Random().nextInt(1000) % asset.length;
          String _image =
              'assets/' + asset[index].substring(asset[index].length - 6);
          asset.removeAt(index);
          return CardModel(
              id: 20 - asset.length - 1, image: _image, key: UniqueKey());
        }).toList();
      }
Nitneuq
  • 3,866
  • 13
  • 41
  • 64

1 Answers1

1

Try:

 List<CardModel> createCards() {
        List<String> asset = [];
        List.filled(10, null).forEach((f) => asset.add('0${(asset.length + 1)}.png'));
        List.filled(10, null).forEach((f) => asset.add('0${(asset.length - 10 + 1)}.png'));
        return List.filled(10, null).map((f) {
          int index = Random().nextInt(1000) % asset.length;
          String _image =
              'assets/' + asset[index].substring(asset[index].length - 6);
          asset.removeAt(index);
          return CardModel(
              id: 20 - asset.length - 1, image: _image, key: UniqueKey());
        }).cast<CardModel>().toList();
      }

Note that when you ommit the type param List(...) the default is dynamic, so: List<dynamic>() equals to List()

If List(N) create a list of type dynamic of size N with all values equals to null, then after null-safety you can replicate this by using List.filled(10, null).

And use cast<T>() to convert the list type to be able to use it as return value which expects the type CardModel.

Alex Rintt
  • 1,618
  • 1
  • 11
  • 18