首页 > 解决方案 > 我如何在 firestore 字段的数组字段中循环并检索最后一个对其具有真实价值的结果?

问题描述

请参阅此图像,模块 0 的锁定等于假,模块 1 的 isLocked 等于真,所以我应该收到“什么是灵性”的名称。

我想检索上一个模块的 isLocked 等于 false 的下一个模块的名称。

标签: javascriptfirebaseflutterdartgoogle-cloud-firestore

解决方案


您可以获取完整列表并检查您的条件。

DocumentSnapshot docSnapshot = Firestore.instance.collection("collectionName").document("docId").get(); //gets the data of your document => replace the collectionName and docId

bool previousIsLockedValue = false; //this keeps track of the previous module isLoked property value and the initial value is false so if the first module's isLocked is true then name will be retrieved
String nameOfModule;

List<dynamic> modules = docSnapshot.data["modules"] //gets the modules list from the document data

for (module in modules){
    if(module["isLocked"] == true && previousIsLockedValue == false){
       nameOfModule = module["name"]; 
       //assigns the module name if the previous isLocked value is false and this 
       //module isLocked value is true

       //Do something with the name ...
    }
    previousIsLockedValue = module["isLocked"];
}


您可以将初始值更改previousIsLockedValue为 true,这样如果 IsLocked 属性为 true,则不会获得第一个模块名称


推荐阅读