I have a question related to Dart Null Safety concept.
Imagine I have a class called Bird
class Bird{
Object character;
Bird();
}
and Pigeon
class Pigeon extends Bird{
String name;
Pigeon();
}
Now, because of Null Safety on Dart, the character object must be instantiated. I want to instantiate that in the constructor because I want the bird class can be testable using Mockito.
But, when I wrote this
class Bird{
late Object character;
Bird(this.character);
}
The Pigeon class shows an error because the Bird class doesn't have any zero-argument constructor.
My workaround is by using a not required argument like this.
class Bird{
late Object character;
Bird({Object? character}) : this.character= character ?? GetIt.I<Object>();;
}
But, I don't like the GetIt part for my default value. Moreover, another programmer may think it is an optional argument because I didn't mark it as required which can lead to an error.
So, how is the best practice to solve this case?
characterto be for aPigeoninstance? Why don't you havePigeonpass an appropriate argument to theBirdconstructor? You also seem to be misunderstanding some other things (e.g., you don't need to uselate, andrequiredis necessary for named arguments to distinguish required from optional named arguments). - jamesdlinlate. It is very bad idea. Try to find a better solution. - mezonicharacterto be forPigeon, we can't really tell how you should initialize it. If it should have the same initial value for allPigeoninstances, then thePigeonconstructor should just call theBirdconstructor with an appropriate argument. Or if it's something that varies acrossPigeons, then it perhaps should be an argument toPigeon's constructor too. - jamesdlin