class Point {
int x;
int y;
Point(this.x, this.y);
Point.zero()
: x = 0,
y = 0;
Point.fromJson({required Map<String, int> json})
:x = json['x'], //Error : `The initializer type 'int?' can't be assigned to the field type 'int'`
y = json['y']; // Error :`The initializer type 'int?' can't be assigned to the field type 'int'`
}
如您所見,json這里的論點是Map<String , int>為什么會在這里出現此錯誤。當兩者都不可為空時?為什么編譯器假設json['x'] = int? ?
uj5u.com熱心網友回復:
因為[]運算子 onMap按規范回傳一個可為空的:
V? operator [](Object? key)給定的值
key,或者null如果key不在地圖中。
https://api.dart.dev/stable/2.15.1/dart-core/Map/operator_get.html
因此,如果您要求的key不是您的,Map您將得到一個null值而不是例外。
如果您 100% 確定json['x']將始終作業并希望應用程式在不是這種情況下崩潰,您可以使用json['x']!. 或者,您需要提供默認值或其他型別的處理,以防這些值不在地圖中。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/420873.html
標籤:
