首页 > 解决方案 > 使用 firebase 的基于角色的 Flutter 应用程序

问题描述

我正在做一个名为事件管理颤振应用程序的大学项目。需要有基于角色的身份验证。

需要的不同角色是:

  1. 用户
  2. 学生协调员
  3. 活动协调员
  4. 主要的
  5. 霍德
  6. 实验室充电

我为不同的角色创建了布尔值。

    bool admin = false;
    bool eCoordinator = false;
    bool labIncharge = false;
    bool principal = false;
    bool hod = false;
    bool sCoordinator = false;

用户数据将具有指定角色的字段:

usersReference.document(gCurrentUser.id).setData({
        "id": gCurrentUser.id,
        "profileName": gCurrentUser.displayName,
        "username": username,
        "url": gCurrentUser.photoUrl,
        "email": gCurrentUser.email,
        "bio": "",
        "timestamp": timestamp,
        "admin": admin,
        "hod": hod,
        "labIncharge": labIncharge,
        "principal": principal,
        "eCoordinator": eCoordinator,
        "sCoordinator": sCoordinator,
      });

它在 Cloud Firestore 中的外观:

在此处输入图像描述

如何通过更改 firebase 的布尔值来获取数据和更新角色?

标签: firebaseflutterdartgoogle-cloud-firestorefirebase-authentication

解决方案


我个人喜欢创建一个可访问的函数,可以调用它来更新给定用户的所有信息(如果你的文档很大,我不推荐这样做)。

Future<void> updateUser(User userData) async {
    // CollectionReference get _usersCollection => _firestore.collection('USERS');
    DocumentReference docRef =
        _usersCollection.document(userData.firebaseUser.uid);
    Map<String, dynamic> userJson = userData.toJson();
    await docRef.setData(userJson, merge: true);

  }
}

您的用例可能会根据您的类结构以及您希望如何使用它而有所改变,但该解决方案的核心在于:

await docRef.setData(userJson, merge: true);

您可以在其中将任何更改的数据写入 Firestore。


推荐阅读