[Flutter/dart] Default value of a class instance in null safety
- M.R

- Dec 29, 2022
- 1 min read
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...






Comments