why there is error while am trying to construct my constructor i want to have a named paramters but not required ones how i can fix this
class Task {
int id;
String title;
String description;
**Task({this.id , this.title , this.description}); // Giving me Errors here**
Map<String , dynamic> toMap()
{
return {
'id' : id,
'title' : title,
'description' : description,
};
}
@override
String toString() {
return 'Task{id: $id, name: $title, age: $description}';
}
}
If you don't want the arguments to be required
, you have to allow them to be null
by adding a question mark to their type, so Dart will know that they don't need to be initialized. Like this:
int? id;
String? title;
String? description;
Another solution is to give them a default value in the constructor, but be careful to assign them values that won't conflict with the rest of your code:
Task({this.id=-1, this.title='Title' , this.description = 'Description'});
Choose the approach that suits you best: you can also use a mix of the two solutions, like making some properties nullable and giving a default value to the others.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.