I have a class Foo
that has a named parameter bar
. I want to make sure bar
always have a value.
I also have an optional variable _bar
, which could be either null or having some value.
I tried passing String? _bar
when constructing Foo
, but it gives me an error. To me if _bar
has value, bar
should uses _bar
‘s value, otherwise bar
would be 'Default'
. But it seems it’s not that easy.
class Foo {
Foo({this.bar = 'Default'});
final String bar;
}
String? _bar;
void main() {
// The argument type 'String?' can't be assigned to the parameter type 'String'.
final value = Foo(bar: _bar);
}
I tried this but I have to specify 'Default'
again while calling it, which is not ideal.
final value = Foo(bar: _bar ?? 'Default');
I’m new to Dart, is there a better way to handle this situation?
2
Answers
You can absolutely do that!
Having both the constructor parameter ánd the field named
bar
can be a bit confusing, so I recommend naming one of them something else (think likebarIn
for the constructor parameter. Though it should work with the code I put aboveTry below code:
If you found variable is null then try to use ?? operator.
?? operator means: if a is not null, it resolves to a. if a is null, it resolves to b.