I'm following along with an online course and the instructor gave this example of code...but it now throws a Null Safety error...
"The parameter 'namePerson' can't have a value of null beccause of its type..but the implicit default value is null'
void main() {
greet(greeting: 'Hey', namePerson: 'Cindy');
}
void greet({String namePerson, String greeting}){
print("$greeting $namePerson");
}
Now after researching this I found I could fix the error in three ways..by placing a ? after the word String...or by placing the word 'required' before the String...or by giving a default value...eg.
void greet({String namePerson = 'Bob', String greeting = 'Sam'}){
I don't really understand though what we should ideally do in a situation like this? I watched a Youtube video on null safety errors'..but it is still a bit beyond my current comprehension level. Can someone explain how and why you would solve this error? Thanks for any help or tips!
CodePudding user response:
You should start by asking you "In the context of my function, are my parameters required of optionnal" ?
Clearly, a function to greet someone should have :
- a required, so non nullable
namePerson
: you must have a name to greet someone. And you cannot have a defaultValue (arbitrary "Bob" ? why ? it doesn't really make sense) - an optional greeting but with a default value, so non nullable also : you must say something to him to greet him
So I'd have it like :
void greet({required String namePerson, String greeting = 'Hello'}){
So basically, you should separate the 2 aspects :
- should the inner body of my function works with a nullable or non nullable value ?
- should my function take a required, optional but non nullable (so with default) value, or a totally optional one (!nullable) ?
Hope that helped
CodePudding user response:
Use null check operator . Your code will run. Use the code like below. Thanks.
void main() {
greet(greeting: 'Hey', namePerson: 'Cindy');
}
void greet({String? namePerson, String? greeting}){
print("$greeting! $namePerson!");
}