我正在使用FirebaseAuth在Flutter应用程序中处理身份验证。但是,我还有其他要针对用户的信息,即组织和角色。这意味着我的数据库中有一个用户集合。我想根据用户是否登录来添加/删除用户。这是我当前的代码:
Main.dart
providers: [
StreamProvider<FirebaseUser>.value(
value: FirebaseAuth.instance.onAuthStateChanged),
ChangeNotifierProvider(
create: (_) => UserProvider(),
),
],
Root.dart
Widget build(BuildContext context) {
var user = Provider.of<FirebaseUser>(context);
bool isLoggedIn = user != null;
if (isLoggedIn) {
return HomeScreen(userId: user.uid);
} else {
return AuthScreen();
}
}
user_model.dart
enum Role { ADMIN, TUTOR, STUDENT }
class User {
final String email;
final String organisation;
final Role role;
User({this.email, this.organisation, this.role});
factory User.fromMap(Map data) {
getRole(String role) {
switch (role) {
case ('ADMIN'):
return Role.ADMIN;
case ('TUTOR'):
return Role.TUTOR;
case ('STUDENT'):
return Role.STUDENT;
default:
return false;
}
}
return User(
email: data['email'] ?? '',
organisation: data['organisation'] ?? '',
role: getRole(data['role']));
}
Map<String, dynamic> toJson() {
return {
'email': email,
'organisation': organisation,
'role': role.toString().split('.').last
};
}
}
user_provider.dart
class UserProvider extends ChangeNotifier {
User _user = User(email: '', organisation: '', role: null);
User get user {
return _user;
}
setUser(User user) {
_user = user;
notifyListeners();
print("_USER: ${user.toJson()}");
}
clearUser() {
_user = User(email: '', organisation: '', role: null);
}
}
database_service.dart
Future<User> getUser(String userID) {
return _db
.collection('users')
.document(userID)
.get()
.then((user) => User.fromMap(user.data));
}