Tom3652
Tom3652

Reputation: 2977

List null safety Flutter

How do you initialize a List<Object> in a constructor when using null safety in flutter without the required keyword ?

I have the following code :

List<String> test = [];
MyConstructor({this.test});

There is a compile error telling me to add the required keyword, but if i do :

List<String> test = [];
MyConstructor({this.test=[]});

This gives me an error that the default value of a named param must be constant.
Of course i can put the required keyword and everything is fine, but in all of my constructors i need to add an empty List it's quite boring because only in 10% of the time i need to pass a non empty List.

Can you simply confirm that the required keyword is the only option ?

Thanks

Upvotes: 5

Views: 9105

Answers (3)

jamesdlin
jamesdlin

Reputation: 90184

  • Use a const initializer:

    List<String> test;
    MyConstructor({this.test = const []});
    

    However, that will be awkward if you need to mutate your List later (and make it impossible if your List member is also final).

  • Mark the parameter as required.

  • Make the parameter (but not the member) nullable:

    List<String> test;
    MyConstructor({List<String>? test})
      : test = test ?? [];
    

    Also see: The default value of an optional parameter must be constant

  • Make both the member and the parameter nullable.

Upvotes: 6

Kartik Patel
Kartik Patel

Reputation: 627

Just add const before empty list, like this:

  List<String> test = [];
  MyConstructor({this.test = const []});

Upvotes: 0

Tirth Patel
Tirth Patel

Reputation: 5756

You could use positional parameter instead.

class MyConstructor {
  List<String> test = [];
  MyConstructor(this.test);
}

You could use const literal as a default value with optional parameter.

class MyConstructor {
  List<String> test = [];
  MyConstructor({this.test = const []});
}

Upvotes: 1

Related Questions