How do I null check or create a null safe block in Flutter?
Here is an example:
class Dog {
final List<String>? breeds;
Dog(this.breeds);
}
void handleDog(Dog dog) {
printBreeds(dog.breeds); //Error: The argument type 'List<String>?' can't be assigned to the parameter type 'List<String>'.
}
void printBreeds(List<String> breeds) {
breeds.forEach((breed) {
print(breed);
});
}
If you try to surround it with an if case you get the same error:
void handleDog(Dog dog){
if(dog.breeds != null) {
printBreeds(dog.breeds); //Error: The argument type 'List<String>?' can't be assigned to the parameter type 'List<String>'.
}
}
If you create a new property and then null check it it works, but it becomes bothersome to create new properties each time you want to null check:
void handleDog(Dog dog) {
final List<String>? breeds = dog.breeds;
if (breeds != null) {
printBreeds(breeds); // OK!
}
}
Is there a better way to do this?
Like the ?.let{}
syntax in kotlin?