0

我只是要开发一个企业级的 Flutter Web 解决方案。所以我决定遵循适当的状态管理包而不是 SetState。这是我的第一个 Flutter Web 应用程序,也是我第一次尝试使用GetX

我将使用 Firestore 实现 Rolebase 授权。一旦用户登录系统,如果他是管理员,他将被重定向到管理页面,否则重定向到用户页面。登录功能正常。但我无法从 Firestore 获得角色。我已经解释了这一切,因为我想知道以下错误的解决方案,并想知道我是否正确地执行了这个状态管理的事情。

该错误清楚地表明“状态不佳:无法在 DocumentSnapshotPlatform 上获取不存在的字段”。但是我怎样才能确定确切的原因呢?有人可以帮助我了解我在哪里犯了错误。

错误 :

[GETX] "AuthController" has been initialized
[GETX] "UserController" has been initialized
[GETX] "GetMaterialController" has been initialized
[GETX] GOING TO ROUTE /login-page
LoginSuccess
Error: Bad state: cannot get a field on a DocumentSnapshotPlatform which does not exist
    at Object.throw_ [as throw] (http://localhost:5000/dart_sdk.js:4328:11)
    at platform_interface_document_snapshot.DocumentSnapshotPlatform.new.get (http://localhost:5000/packages/cloud_firestore_platform_interface/src/platform_interface/platform_interface_write_batch.dart.lib.js:652:19)
    at cloud_firestore.DocumentSnapshot.__.get (http://localhost:5000/packages/cloud_firestore/cloud_firestore.dart.lib.js:697:73)
    at cloud_firestore.DocumentSnapshot.__._get (http://localhost:5000/packages/cloud_firestore/cloud_firestore.dart.lib.js:700:19)
    at new user_model.UserModel.fromDocumentSnapshot (http://localhost:5000/packages/equipment_management_system/models/user_model.dart.lib.js:47:32)
    at database.Database.new.getUser (http://localhost:5000/packages/equipment_management_system/views/pages/login_page.dart.lib.js:3180:16)
    at getUser.next (<anonymous>)
    at http://localhost:5000/dart_sdk.js:37593:33
    at _RootZone.runUnary (http://localhost:5000/dart_sdk.js:37447:58)
    at _FutureListener.thenAwait.handleValue (http://localhost:5000/dart_sdk.js:32424:29)
    at handleValueCallback (http://localhost:5000/dart_sdk.js:32971:49)
    at Function._propagateToListeners (http://localhost:5000/dart_sdk.js:33009:17)
    at _Future.new.[_completeWithValue] (http://localhost:5000/dart_sdk.js:32852:23)
    at async._AsyncCallbackEntry.new.callback (http://localhost:5000/dart_sdk.js:32874:35)
    at Object._microtaskLoop (http://localhost:5000/dart_sdk.js:37708:13)
    at _startMicrotaskLoop (http://localhost:5000/dart_sdk.js:37714:13)
    at http://localhost:5000/dart_sdk.js:33226:9

认证控制器:

  handleAuthChanged(isLoggedIn) async {
    final UserController userController = Get.put<UserController>(UserController());
    if (isLoggedIn == false) {
      Get.offAllNamed(LoginPageRoute);
    } else {
      print("LoginSuccess");
      userController.user = await Database().getUser(user.value.uid).then((value){
        print(userController.user.id);
        if(userController.user.role == "Admin"){
          Get.offAllNamed(AdminHomePageRoute);
        }else{
          Get.offAllNamed(UserHomePageRoute);
        }
        return;
      });
    }
  }

用户模型

class UserModel{
  String id;
  String name;
  String role;

  UserModel({id, name, email, role});

  UserModel.fromDocumentSnapshot(DocumentSnapshot doc){
    id = doc["id"];
    name = doc["name"];
    name = doc["role"];
  }

}

用户控制器

class UserController extends GetxController{
  Rx<UserModel> _userModel = UserModel().obs;
  UserModel get user => _userModel.value;
  set user(UserModel value) => this._userModel.value = value;
  void clear(){
    _userModel.value = UserModel();
  }
}

数据库服务

class Database{
  final FirebaseFirestore _firebaseFirestore = FirebaseFirestore.instance;

  Future<bool> createNewUser(UserModel user) async {
    await _firebaseFirestore.collection("users").doc(user.id).set({
      "name" : user.name,
      "role" : user.role,
    }).catchError((onError){
      Get.snackbar(
        "", "",
        titleText: Text("An error occurred while connecting to the database", style: TextStyle(fontFamily: "Poppins", fontWeight: FontWeight.bold, fontSize: 16)),
        messageText: Text(onError.message, style: TextStyle(fontFamily: "Poppins")),
        colorText: primaryColor,
        backgroundColor: Colors.white.withOpacity(0.5),
        margin: EdgeInsets.only(top: 20, left: 20, right: 20),
        barBlur: 10,
      );
      return false;
    });
    return true;
  }

  Future<UserModel> getUser(String uid) async{
    DocumentSnapshot doc = await _firebaseFirestore.collection("users").doc(uid).get().catchError((onError){
      Get.snackbar(
        "", "",
        titleText: Text("An error occurred while retrieving data", style: TextStyle(fontFamily: "Poppins", fontWeight: FontWeight.bold, fontSize: 16)),
        messageText: Text(onError.message, style: TextStyle(fontFamily: "Poppins")),
        colorText: primaryColor,
        backgroundColor: Colors.white.withOpacity(0.5),
        margin: EdgeInsets.only(top: 20, left: 20, right: 20),
        barBlur: 10,
      );
    });
      return UserModel.fromDocumentSnapshot(doc);
  }
}

Firestore 集合

在此处输入图像描述

4

2 回答 2

1
class UserModel {
  String id;
  String name;
  String role;

  UserModel({id, name, email, role});

  UserModel.fromDocumentSnapshot(DocumentSnapshot doc) {
    id = doc.data().containsKey("id") ? doc.data()["id"] : '';
    name = doc.data().containsKey("name") ? doc.data()["name"] : '';
    role = doc.data().containsKey("role") ? doc.data()["role"] : '';
  }
}
于 2021-07-08T04:35:12.367 回答
0

我最近有同样的错误。我最近升级了几个 Firebase 软件包(cloud_firestore:^0.14.1+3,firebase_auth:^0.18.1+2,firebase_dynamic_links:^0.6.0+2,firebase_storage:^4.0.1)。之后,清理所有不推荐使用的方法等。我开始得到相同的“无法在 DocumentSnapshotPlatform 上获取不存在的字段”。

我最终发现,如果我将所有引用从 doc["fooBar"] 更改为 doc.data()["fooBar"] 就可以解决问题。尝试将您的代码更改为以下内容:

class UserModel{
    String id;
    String name;
    String role;

    UserModel({id, name, email, role});

    UserModel.fromDocumentSnapshot(DocumentSnapshot doc){
        id = doc.data()["id"] // previously doc["id"];
        name = doc.data()["name"] // previously doc["name"];
        name = doc.data()["role"] // previously doc["role"];
    }
}

进一步阅读(https://pub.dev/packages/cloud_firestore/changelog)后,我发现以下关于版本 0.14.0^ 的 DocumentSnapshots 的注释

“文档快照:

BREAKING:get data getter 现在是一个 data() 方法。……”

于 2020-10-21T11:09:59.123 回答