flutter 必须分配不可为空的局部变量userModel

gkl3eglg  于 2023-03-03  发布在  Flutter
关注(0)|答案(1)|浏览(165)
FutureEither<UserModel> signInWithGoogle() async {
    try {
      final GoogleSignInAccount? googleUser = await _googleSignIn.signIn();
      final GoogleSignInAuthentication? googleAuth =
          await googleUser?.authentication;
      final credential = GoogleAuthProvider.credential(
        accessToken: googleAuth?.accessToken,
        idToken: googleAuth?.idToken,
      );

      final userCredential = await _auth.signInWithCredential(credential);

      final user = userCredential.user!;
      UserModel userModel;
      if (userCredential.additionalUserInfo!.isNewUser) {
        userModel = UserModel(
          email: user.email!,
          id: user.uid,
          img: user.photoURL!,
          username: user.displayName!,
        );
        await saveUserData(userModel);
       
      } else {
        final userDoc = await getUserData(user.email!);
        userDoc.fold((l) => null, (r) {
          userModel = UserModel.fromJson(r);
         
        });
      }
      return right(userModel);
    } on FirebaseAuthException catch (e, st) {
      return left(
        Failure(e.message ?? "Bilinmeyen bir hata oluştu", st),
      );
    } catch (e, st) {
      return left(
        Failure(e.toString(), st),
      );
    }
  }

我做了赋值,但仍然面临空值问题

42fyovps

42fyovps1#

您可以使用late在读取时间之前赋值,或者使其可为空。

late UserModel userModel;

UserModel? userModel;

关于understanding-null-safety的更多信息

相关问题