I made a class HelloWorld
with a named constructer which accepts a single parameter named test
which also has default value of Default Value
. Here is my code:
import 'dart:core';
class HelloWorld {
final String test;
const HelloWorld({
this.test = 'Default Value',
});
}
void main() {
const Map<String, dynamic> _json = {'hello': 'world'};
const _helloWorld = HelloWorld(test: _json['test']);
print(_helloWorld.test);
}
Then I made a map named _json
which has only one key hello
. Finally I tried to get the value of key test
which obviously doesn't exist in _json
which will return null
. Despite having the default value for the test
parameter in the named constructor, I still get this compilation error:
lib/main.dart:13:23:
Error: Constant evaluation error:
const _helloWorld = HelloWorld(test: _json['test']);
^
lib/main.dart:13:45:
Info: The method '[]' can't be invoked on '<String, dynamic>{"hello": "world"}' in a constant expression.
const _helloWorld = HelloWorld(test: _json['test']);
^
lib/main.dart:13:9:
Info: While analyzing:
const _helloWorld = HelloWorld(test: _json['test']);
^
Error: Compilation failed.
Dart version: Dart SDK version: 2.14.4 (stable) (Wed Oct 13 11:11:32 2021 +0200) on "macos_x64"