参数'firebaseFirestore'因为类型的原因不能有'null'的值,但是在flutter中隐含的默认值为'null'

The parameter 'firebaseFirestore' can't have a value of 'null' because of its type, but the implicit default value is 'null' in flutter

我声明了两个 FirebaseFirestoreFireBaseAuth 类型的变量,现在我面临空安全错误。我在我的 class 中使用构造函数,并将它们作为参数传递,但出现错误 - The parameter 'firebaseFirestore' can't have a value of 'null' because of its type, but the implicit default value is 'null' in flutterThe parameter 'firebaseAuth' can't have a value of 'null' because of its type, but the implicit default value is 'null' in flutter.

构成我的问题的代码部分是-

import 'package:flutter_instagram_clone_final/repositories/repositories.dart';
import 'package:firebase_auth/firebase_auth.dart' as auth;

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;

然后我尝试用实例初始化它,比如 -

    FirebaseFirestore firebaseFirestore = FirebaseFirestore.instance,

但它给我一个错误 - The default value of an optional parameter must be constant.

To guarantee that you never see a null parameter with a non-nullable type, the type checker requires all optional parameters to either have a nullable type or a default value.

Understanding null safety | Dart

您需要使 firebaseFirestorefirebaseAuth 可以为空,因为它们是可选的并且它们的默认值不是常量。

您可以通过在类型后面添加 ? 来实现。

像这样:

    FirebaseFirestore? firebaseFirestore,
    auth.FirebaseAuth? firebaseAuth,

因此您的构造函数可以更新为:

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