skip to Main Content

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


  1. 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;
    }
    
    Login or Signup to reply.
  2. Try below code:

    class Foo {
      Foo({this.bar = 'Default'});
    
      final String bar;
    }
    
    void main() {
      final value = Foo(bar: Foo().bar);
      final value1 = Foo(bar: Foo().bar ?? 'Default');
      print(value.bar);
      print(value1.bar);
    }
    

    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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search