The initializer type 'AuthRepository?' can't be assigned to the field type 'AuthRepository' in flutter

Issue

The error is coming on line 6 (in the first code snippet or the main code part), on authRepository part.

The main code –

class AuthBloc extends Bloc<AuthEvent, AuthState> {
  final AuthRepository  _authRepository;
  var v;
  AuthBloc({
    @required AuthRepository? authRepository
  }) : _authRepository = authRepository super(AuthState.unknown());

And here is the snippet of AuthRepository

class AuthRepository extends BaseAuthRepository {

  final FirebaseFirestore _firebaseFirestore;
  final auth.FirebaseAuth _firebaseAuth;

  AuthRepository({
    FirebaseFirestore? firebaseFirestore,
    auth.FirebaseAuth? firebaseAuth,
  })  : _firebaseFirestore = firebaseFirestore ?? FirebaseFirestore.instance,
        _firebaseAuth = firebaseAuth ?? auth.FirebaseAuth.instance;

Solution

You’re trying to assign a nullable variable to a non-nullable variable. Use syntactic sugar (this.var syntax) for the constructor and use positional parameter.

class AuthBloc extends Bloc<AuthEvent, AuthState> {
  final AuthRepository  _authRepository;
  var v;
  AuthBloc(this._authRepository) : super(AuthState.unknown());
}

Other Solution

If you still want to use the required named parameter with a private member, make the _authRepository a nullable variable, that would require changes wherever you’ve used that variable (_authRepository).

class AuthBloc extends Bloc<AuthEvent, AuthState> {
  final AuthRepository?  _authRepository;
  var v;
  AuthBloc({
    @required AuthRepository? authRepository
  }) : _authRepository = authRepository super(AuthState.unknown());
}

Answered By – Tirth Patel

Answer Checked By – Jay B. (FlutterFixes Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *