Reputation: 643
Hi Im following one of the yt tutorials and when I try to make a model this error occurs what is my best approach to solve this problem. I cannot put required because some values do take null. My project is based I'm taking global API I found on net similar to http://www.omdbapi.com/ (Im not using this but this is just a point of refference) and when I do so I get this error:
The parameter 'title' can't have a value of 'null' because of its type, but the implicit default value is 'null'.
Try adding either an explicit non-'null' default value or the 'required' modifier.dartmissing_default_value_for_parameter
{String title}
This is my books class:
class Book{
String name;
String title;
String city;
Book(
{this.name,
this.name,
this.name});
factory Book.fromJson(Map<String,dynamic> json){
return Book(
name: json['name'] as String,
title: json['title'] as String,
name: json['name'] as String,
);
}
}
What is the best solution to this problem because when they do it this way they have no error at all. Looking forward to your answers
Thanks in advance
Upvotes: 3
Views: 4451
Reputation: 643
Ok so the solution for my problems was quite strange indeed. All I had to do is whitch from sdk: ">=2.15.0 <3.0.0"
to sdk: ">=2.7.0 <3.0.0"
Upvotes: 0
Reputation: 1313
As the error message suggests you can either:
Option 1: Add the 'required' modifier because the default_value_for_parameter is missing:
Book({
required this.name,
required this.title,
required this.city
});
Option 2: Try adding either an explicit non-'null' default value
String title = ""; // Empty string as a default value
Option 3: Make the value nullable (Be careful with this, only do it if the value should be nullable)
String? title;
As you mentioned, that they can be null, your code needs to reflect that as well. Therefore, you have to make your parameters nullable by adding the "?" after the type annotation. Just as a reminder, use null checks whereever you need a non-nullable value ( if(value != null) > then do something ) to avoid run-time null errors :)
Upvotes: 1
Reputation: 453
You are using named parameters and in your case they can be null.
You need to add required
to the parameters in the constructor:
class Book{
String name;
String title;
String city;
Book({
required this.name,
required this.name,
required this.name
});
factory Book.fromJson(Map<String,dynamic> json){
return Book(
name: json['name'] as String,
title: json['title'] as String,
name: json['name'] as String,
);
}
}
Or if the parameters can be null:
class Book{
String? name;
String? title;
String? city;
Book({
this.name,
this.name,
this.name
});
factory Book.fromJson(Map<String,dynamic> json){
return Book(
name: json['name'] as String?,
title: json['title'] as String?,
name: json['name'] as String?,
);
}
}
Upvotes: 3