Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter: Default assignment of List parameter in a constructor

Tags:

flutter

dart

Is it possible to assign a constant value to an optional parameter of datatype List while defining a constructor. for example,

`class sample{   final int x;   final List<String> y;   sample({this.x = 0; this.y = ["y","y","y","y"]});  }` 

the above code throws an error focused at y assignment saying Default values of an optional parameter must be constant

what is the reason for this error? how else can I assign a default value to the List?

like image 283
Naveen Avatar asked Jan 20 '19 17:01

Naveen


People also ask

How do you pass optional parameters in Flutter?

Named optional parameters You can call getHttpUrl with or without the third parameter. You must use the parameter name when calling the function. You can specify multiple named parameters for a function: getHttpUrl(String server, String path, {int port = 80, int numRetries = 3}) { // ... }

How do you initialize an empty list in darts?

To create an empty list, use [] for a growable list or List. empty for a fixed length list (or where growability is determined at run-time). The created list is fixed-length if length is provided. The list has length 0 and is growable if length is omitted.

How do I set default value in constructor Dart?

Dart/Flutter Constructor default value For the constructors with either Named or Positional parameters, we can use = to define default values. The default values must be compile-time constants. If we don't provide value, the default value is null.


1 Answers

Default values currently need to be const. This might change in the future.

If your default value can be const, adding const would be enough

class sample{   final int x;   final List<String> y;   sample({this.x = 0; this.y = const ["y","y","y","y"]}); } 

Dart usually just assumes const when const is required, but for default values this was omitted to not break existing code in case the constraint is actually removed.

If you want a default value that can't be const because it's calculated at runtime you can set it in the initializer list

class sample{   final int x;   final List<String> y;   sample({this.x = 0; List<String> y}) : y = y ?? ["y","y","y","y"]; } 
like image 98
Günter Zöchbauer Avatar answered Sep 21 '22 13:09

Günter Zöchbauer