문제

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
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top