Home > OS >  There is a line above "List" and I get an error. How can i assign a clean "List"
There is a line above "List" and I get an error. How can i assign a clean "List"

Time:09-21

    void main() {
  var urunler = new List(5);
  urunler[0] = "Laptop";
  urunler[1] = "Mouse";
  urunler[2] = "Keyboard";
  urunler[3] = "Monitor";
  urunler[4] = "Mic";

  print(urunler);
} 

lib/main.dart:2:21: Error: Can't use the default List constructor. Try using List.filled instead. var urunler = new List(5); ^ Failed to compile application.

CodePudding user response:

  • The default 'List' constructor isn't available when null safety is enabled.

Try this:

void main() {
  var urunler = List<String>.filled(5,"",growable: false);
  urunler[0] = "Laptop";
  urunler[1] = "Mouse";
  urunler[2] = "Keyboard";
  urunler[3] = "Monitor";
  urunler[4] = "Mic";

  print(urunler);
}

https://api.dart.dev/stable/2.14.2/dart-core/List/List.filled.html

CodePudding user response:

For a List, its better if you declare what kind of List you want to make. I dont think you can create a clean list because we need inital value for it, or you can create a blank list, and use a function to return the data inside. But from the code above, this is the best approach I can think right now.

  List<String> urunler = ["Laptop", "Mouse", "Keyoboard"];
  • Related