[Flutter/dart] Default value of a class instance in null safety
Overview
When creating an instance of a certain class, there are cases where it is optional to set arguments to the instance, and if not set, we want to set a default value.
I had a little trouble with this pattern after introducing null safety, so I'll summarize it.
Promblem
For primitive types such as int, default values can be specified in constructor.
class SomeClass{
int a;
SomeCless({this.a = 0});
}
However, this is not possible for instances of other classes.
class SomeClass{
OtherClass other;
SomeCless({this.other = Other(b:1)}); //compile error
}
class OtherClass{
final int b;
OtherClass({this.b});
}
Without null safety, it was written in the following way, but it is no longer possible.
class SomeClass{
OtherClass other;
SomeCless({OtherClass o}):
other = o?? OtherClass(b:1);
}
Solution
Make the argument a nullable type and check null and set default value in the initializer.
class SomeClass{
OtherClass other;
SomeCless({OtherClass? o}):
other = o?? OtherClass(b:1);
}
Lastly
With null safety, the way of writing that had no problem until now becomes an error, so I'm confused in various situations...
Recent Posts
See AllWhat want to do I want to create an input form using TextField. For example, if the input content is a monetary amount, I would like to...
What want to do There is a variable that remain unchanged once the initial value is determined. However, it cannot be determined yet when...
What want to do As the title suggests. Place two widgets in one line on the screen One in the center of the screen and the other on the...
コメント