錯誤:Non-nullable instance field id must be initialised.
來源:Picture.fromMap
import 'dart:typed_data'; // Uint8List
class Picture {
int id;
String title;
Uint8List? picture;
Picture({this.id = 0, this.title = "", this.picture });
Picture.fromMap(Map map) {
id = map[id];
title = map[title];
picture = map[picture];
}
Map<String, dynamic> toMap() => {
"id": id,
"title": title,
"picture" : picture,
};
}
傳遞給函式引數時的初始化方式是什么Map,或者如何解決這個錯誤?
uj5u.com熱心網友回復:
late當您知道它稍后將被初始化時使用關鍵字。否則 int id=0;對其他不可為空的欄位使用和類似作為默認初始化
class Picture {
late int id;
late String title;
Uint8List? picture;
Picture({this.id = 0, this.title = "", this.picture });
Picture.fromMap(Map map) {
id = map[id];
title = map[title];
picture = map[picture];
}
Map<String, dynamic> toMap() => {
"id": id,
"title": title,
"picture" : picture,
};
}
uj5u.com熱心網友回復:
因為你在Picture.fromMap構造函式體中初始化。試試下面的代碼。
import 'dart:typed_data'; // Uint8List
class Picture {
int id;
String title;
Uint8List? picture;
Picture({this.id = 0, this.title = "", this.picture});
factory Picture.fromMap(Map map) {
return Picture(
id: map["id"],
title: map["title"],
picture: map["picture"],
);
}
Map<String, dynamic> toMap() => {
"id": id,
"title": title,
"picture": picture,
};
}
或者
import 'dart:typed_data'; // Uint8List
class Picture {
int id;
String title;
Uint8List? picture;
Picture({this.id = 0, this.title = "", this.picture});
Picture.fromMap(Map map)
: id = map["id"],
title = map["title"],
picture = map["picture"];
Map<String, dynamic> toMap() => {
"id": id,
"title": title,
"picture": picture,
};
}
uj5u.com熱心網友回復:
此類實體欄位分配有 2 個選項。
- 命名生成建構式
- 命名工廠建構式
生成式建構式: 您可以在 (:) 冒號后面使用初始化串列
工廠構造器: 您可以使用任何業務邏輯并在構造器主體中初始化您的實體欄位(變數),就像常規函式一樣。
示例:
class User {
String name;
int id;
**// Named generative constructor**
User.fromJson(Map<String,Object> json)
: name = json['name'] as String,
id = json['id'] as int;
**// Factory constructor**
factory User.fromJson(Map<String,Object> json) {
final id = json['id'] as int;
final name = json['name'] as String;
return User(id:id, name:name);
}`
uj5u.com熱心網友回復:
在您的代碼塊中,您沒有定義可為空的變數。您必須定義所有具有 null 安全性的變數。
int? id;
String? title;
Uint8List? picture;
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/459948.html
上一篇:使用分隔符按百分比排列行布局
下一篇:如何實作自定義對話框?
