将 Firebase 用户模型升级为空安全

Upgrading Firebase User model to null safety

我终于冒险将我的应用程序升级到 Null Safety,但在升级以下代码时遇到问题。

(如果不是很明显,我将 Firebase 用户模型映射到本地 AppUser 模型,并将其用作整个应用程序的身份验证包装器。)

class AuthService with ChangeNotifier {
  final FirebaseAuth _auth = FirebaseAuth.instance;
  late AuthResultStatus _authStatus;

  Stream<AppUser> get appUser {
    return _auth.userChanges().map(_appUserFromFirebaseUser);
  }

AppUser _appUserFromFirebaseUser(User user) {
    return user != null
        ? AppUser(
            uid: user.uid,
            creationTime: user.metadata.creationTime,
            email: user.email,
            emailVerified: user.emailVerified,
          )
        : null;
  }
}


class AppUser {
  final String? uid;
  final DateTime? creationTime;
  final String? email;
  final bool? emailVerified;

  AppUser({
    this.uid,
    this.creationTime,
    this.email,
    this.emailVerified,
  });
}

如何 return 本地 AppUser 模型或 null?感谢您的指点。

你自己说了,你想要一个AppUser或者null,那就是AppUser?。只需在方法和流中进行此更改即可。

class AuthService with ChangeNotifier {
  final FirebaseAuth _auth = FirebaseAuth.instance;
  late AuthResultStatus _authStatus;

  Stream<AppUser?> get appUser {
    return _auth.userChanges().map(_appUserFromFirebaseUser);
  }

AppUser? _appUserFromFirebaseUser(User user) {
    return user != null
        ? AppUser(
            uid: user.uid,
            creationTime: user.metadata.creationTime,
            email: user.email,
            emailVerified: user.emailVerified,
          )
        : null;
  }
}

使用这个:

AppUser? _appUserFromFirebaseUser(User? user) {
    return user != null
        ? AppUser(
            uid: user!.uid,
            creationTime: user!.metadata.creationTime,
            email: user!.email,
            emailVerified: user!.emailVerified,
          )
        : null;
  }
}