Flutter该方法在null上被调用。接收者:null

时间:2020-02-29 02:31:21

标签: firebase authentication flutter dart null

我正在使用Firebase API制作带有Flutter的登录页面。但是,每当我单击“登录”或“注册”按钮时,就会显示一个错误,指出该方法是在null上调用的。

这是SubmitForm方法的代码

AuthMode _authMode = AuthMode.Login;

User _user = User();
FirebaseApi _api;

void _submitForm() {
    if (!_formKey.currentState.validate()) {
      return;
    }

    _formKey.currentState.save();

    AuthNotifier authNotifier =
        Provider.of<AuthNotifier>(context, listen: false);

    if (_authMode == AuthMode.Login) {
      print('Email: ${_user.email}, Password: ${_user.password}');
      _api.login(_user, authNotifier);
    } else {
      _api.signup(_user, authNotifier);
    }
  }

这是我的用户类别

class User {
  String username;
  String email;
  String password;

  User();
}

authNotifier类: 导入'package:firebase_auth / firebase_auth.dart'; 导入'package:flutter / widgets.dart';

class AuthNotifier with ChangeNotifier {
  FirebaseUser _user;

  FirebaseUser get user => _user;

  void setUser(FirebaseUser user) {
    this._user = user;
    notifyListeners();
  }
}

和firebase_api类:

class FirebaseApi {
  login(User user, AuthNotifier authNotifier) async {
    AuthResult authResult = await FirebaseAuth.instance
        .signInWithEmailAndPassword(email: user.email, password: user.password)
        .catchError((error) => print(error.code));

    if (authResult != null) {
      FirebaseUser firebaseUser = authResult.user;

      if (firebaseUser != null) {
        print("Log In: $firebaseUser");
        authNotifier.setUser(firebaseUser);
      }
    }
  }

  signup(User user, AuthNotifier authNotifier) async {
    AuthResult authResult = await FirebaseAuth.instance
        .createUserWithEmailAndPassword(
            email: user.email, password: user.password)
        .catchError((error) => print(error.code));

    if (authResult.user != null) {
      UserUpdateInfo updateInfo = UserUpdateInfo();
      updateInfo.displayName = user.username;

      FirebaseUser firebaseUser = authResult.user;

      if (firebaseUser != null) {
        await firebaseUser.updateProfile(updateInfo);
        await firebaseUser.reload();

        print("Sign up $firebaseUser");

        FirebaseUser currentUser = await FirebaseAuth.instance.currentUser();
        authNotifier.setUser(currentUser);
      }
    }
  }

  signout(AuthNotifier authNotifier) async {
    await FirebaseAuth.instance
        .signOut()
        .catchError((error) => print(error.code));

    authNotifier.setUser(null);
  }

  getCurrentUser(AuthNotifier authNotifier) async {
    FirebaseUser firebaseUser = await FirebaseAuth.instance.currentUser();

    if (firebaseUser != null) {
      authNotifier.setUser(firebaseUser);
    }
  }
}

1 个答案:

答案 0 :(得分:0)

您必须构造_api变量,否则它将是null

FirebaseApi _api = FirebaseApi();