Home > OS >  Typing lists in function arguments in Dart
Typing lists in function arguments in Dart

Time:12-07

It's great that Dart allows us to type arguments for functions:

void createPerson(String name, int age, sayHey: Function) {
  /* Create */
}

But what if the argument should be a list of said type. I.e:

void createPeople(List<?> peopleConfigs) {
  /* Create multiple */
}

What's the best way to type peopleConfigs here? And will tooling like code hint/completion still work when passing the arguments?

I know I can just use List<Map<String, dynamic>> but I wonder if there's a more type-safe way that would throw compile-time errors if keys were used that shouldn't be.

I'm coming from TypeScript where this is pretty straight forward:

createPeople(peopleConfigs: {name: string, age: number, sayHey: () => void}[]): void {
  /* Create multiple */
}

CodePudding user response:

If you want your peopleConfigs to hold some functions with defined type signature:

You can use typedef for this:

typedef PersonConfig = void Function(
  String name,
  int age,
  Function sayHey,
);

//ok function
void create1(String name, int age, Function sayHey) {}

//not ok function
void create2(String name, double age, Function sayHey) {}

void createPeople(List<PersonConfig> peopleConfigs) {
  //some logic
}

void main() {
  createPeople(<PersonConfig>[
    create1, //<--- ok
    (String name, int age, Function sayHey) {}, //<--- ok
    create2, // <--- error
  ]);
}

If you want your peopleConfigs to hold class instances:

class PersonConfig {
  final String? name;
  final int? age;
  final Function? sayHey;

  PersonConfig({
    this.name,
    this.age,
    this.sayHey,
  });
}

void createPeople(List<PersonConfig> peopleConfigs) {
  //some logic
}

void main() {
  createPeople(<PersonConfig>[
    PersonConfig(name: "", age: 0, sayHey: () => "hi"),
  ]);
}

CodePudding user response:

You can create a type, then you can define a list of said type as a parameter:

class Parameters {
  final String name;
  final int age;
  final Function sayHey;
  
  Parameters({required this.name, required this.age, required this.sayHey});
}

void someFunction(List<Parameters> parameters) {
  print(parameters);
}

void main() {
  someFunction([
    Parameters(name: "Joe", age: 21, sayHey: () => print("hi") ),
    Parameters(name: "Suzi", age: 24, sayHey: () => print("hello") ),
  ]);
}
  • Related