Error: Non-nullable instance field id must be initialised.
Source: 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,
};
}
What is the way to initialise Map
when being passed to a function parameter, or how to solve this error?
CodePudding user response:
Use keyword late
when you know that it will be initialized later. otherwise use int id=0;
and similar for other non nullable fields as a default initialization
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,
};
}
CodePudding user response:
Because you init at the Picture.fromMap
constructor function body. Try the below code.
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,
};
}
OR
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,
};
}
CodePudding user response:
In your code block, you didn't define variable nullable. You have to define all variables with null safety.
int? id;
String? title;
Uint8List? picture;