Search code examples
dartdart-null-safety

Dart: Use non-constant value as default constructor parameter


I would like to use FirebaseAuth.instance (a non-constant value) as a default parameter in a constructor.

I have this class:

class MailAuth {
  final FirebaseAuth firebaseAuth = FirebaseAuth.instance;

  MailAuth();

  // methods using firebaseAuth
}

Now I want to unit-test this class, so I want to mock firebaseAuth and inject the mock in the constructor. It should be a named parameter with the default value of FirebaseAuth.instance. I tried something like this:

class MailAuth {
  final FirebaseAuth firebaseAuth;

  MailAuth({this.firebaseAuth = FirebaseAuth.instance});

  // methods using firebaseAuth 
}

But this doesn't work because FirebaseAuth.instance is not a constant.

How can I achieve this behaviour?


Solution

  • While the accepted answer works, you don't really have to "Use a null value as sign to use your default value".

    With sound null safety, you might not want to make your instance variable of nullable type (final FirebaseAuth? firebaseAuth) for several reasons.

    Instead of starting with null or having a nullable type(?), just declare your instance variable as late, instead of final, indicating that you do want to initialise it, ensuring you initialise it in the constructor with a default value if none is passed in invocation.

    So now you will get:

    class MailAuth {
      late FirebaseAuth firebaseAuth;
    
      MailAuth({firebaseAuth}) {
        this.firebaseAuth = this.firebaseAuth ?? FirebaseAuth.instance;
      }
    
      // methods using firebaseAuth 
    }