skip to Main Content

I have a simple class like this:

class Staff {
  final String name;
  final String id;

  Staff({this.name, this.id});
}

Then following a tutorial article on applying BLoC, I put it in State class, like this:

class SignInState {
  final String href;
  final Staff staff;

  SignInState({this.href = '', this.staff= Staff(name:'', id:'')});
}

But in this.staff= Staff(name: '', id: ''), I keep getting error:

The default value of an optional parameter must be constant.

final Staff staff = Staff(name: '', id: '') works.

Why doesn’t it work on that line and produces an error instead?

2

Answers


  1. In your example, the default value for the staff parameter is not a compile-time constant because it involves the instantiation of a new Staff object using constructor arguments (name and id) that are not constants.

    You can use a non-optional constructor parameter with a default value:

    class Staff {
      Staff({this.name = '', this.id = ''});
    
      final String name;
      final String id;
    }
    
    class SignInState {
      SignInState({this.href = '', Staff? staff}) : this.staff = staff ?? Staff();
    
      final String href;
      final Staff staff;
    }
    
    Login or Signup to reply.
  2. I think you can have a constant constructor for Staff

    class Staff {
      final String name;
      final String id;
    
      const Staff({this.name, this.id});
    }
    

    Then you can use const for SignInState

    class SignInState {
      final String href;
      final Staff staff;
    
      const SignInState({this.href = '', this.staff = const Staff(name: '', id: '')});
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search