Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading