Home > Software design >  Why does dart ask me to declare an unnecessary argument?
Why does dart ask me to declare an unnecessary argument?

Time:10-14

Why do I need to declare a variable of type int called "idx" if it does not serve any purpose in the generate funciton below?

Random r2 = new Random();
  var list = List<int>.generate(5, (int idx) => r2.nextInt(100));

If I do not declare it dart gives me the following error

The argument type 'int Function()' can't be assigned to the parameter type 'int Function(int)'

CodePudding user response:

The List.generate has been defined as

List.generate(int length, E generator(int index),
      {bool growable = true});

So you need to provide a function to use List.generate.

If you like to ignore it you can use _.

 List<int>.generate(5, (_) => r2.nextInt(100));

CodePudding user response:

Dart is type-safe, so it expects that the type signatures of arguments match. You can't pass a int Function() where an int Function(int) is expected.

Must it be that way? No. Since the int argument is clearly unused, the compiler conceivably could automatically transform () => r2.nextInt(100) into (_) => (() => r2.nextInt(100))(). However, doing so might hide mistakes where a wrong function is passed. Dart often favors being explicit.

  • Related