I am making a login page with flutter that uses the firebase api. But whenever I click on the login or signup button, it shows me an error that The method was called on null.
Here's the code for submitForm method
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);
}
}
Here's my user class
class User {
String username;
String email;
String password;
User();
}
The authNotifier class: import 'package:firebase_auth/firebase_auth.dart'; import 'package:flutter/widgets.dart';
class AuthNotifier with ChangeNotifier {
FirebaseUser _user;
FirebaseUser get user => _user;
void setUser(FirebaseUser user) {
this._user = user;
notifyListeners();
}
}
And the firebase_api class:
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);
}
}
}
你必须构造_api
变量,否则它将是一个null
。
FirebaseApi _api = FirebaseApi();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.