Why is this not an error in Dart?
List<String> listA = ['aa', 1, 'cc']; //not compile time error, not run time error??
I am using Dart Editor.
Writing List<String> listA = ['aa', 1, 'cc'];
is like writing List<String> listA = <dynamic>['aa', 1, 'cc'];
. The runtimeType
of ['aa', 1, 'cc']
is List
which is compatible with the type annotation List<String>
you used.
If you want to define a list of String
to have a warning in editor and an error at runtime you should prefer :
List<String> listA = <String>['aa', 'cc'];
// or
final listA = <String>['aa', 'cc'];
To better understand here's some samples :
print((['aa', 1, 'cc']).runtimeType); // List
print((['aa', 'cc']).runtimeType); // List
print((<dynamic>['aa', 'cc']).runtimeType); // List
print((<String>['aa', 'cc']).runtimeType); // List<String>
List<int> l1 = ['aa', 1, 'cc']; // ok
List<int> l2 = ['aa', 'cc']; // ok
List<int> l3 = <dynamic>['aa', 'cc']; // ok
List<int> l4 = <String>['aa', 'cc']; // warning in editor + runtime error