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?
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}) { // ... }
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.
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.
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"]; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With