Search code examples
flutterdart

Passing an optional value as a constructor parameter with default value in Dart?


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?


Solution

  • You can absolutely do that!

    class Foo {
      const Foo({String? bar}) : bar = bar ?? 'Default';
      final String bar;
    }
    

    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 like barIn for the constructor parameter. Though it should work with the code I put above

    class Foo {
      const Foo({String? barIn}) : bar = barIn ?? 'Default';
      final String bar;
    }