【发布时间】:2020-09-18 06:51:43
【问题描述】:
在我的 Flutter 代码中,我有一个链接到汽车列表的下拉列表。选择汽车后,我想检索与汽车关联的品牌。但由于某种原因,用于读取 Firebase RTDB 的代码对于索引 0、索引 1 和索引 2 及更高版本必须不同。从我的 RTDB 中获取的示例树如下:
[ {
"Brand" : "Alfa Romeo",
"Car" : "Alfa Romeo Guilia 2.9 V6 BiTurbo Quadrifoglioli Automatic Petrol Sedan RWD",
}, {
"Brand" : "Alfa Romeo",
"Car" : "Alfa Romeo Guilia 2.0T Standard Automatic Petrol Sedan RWD",
}, {
"Brand" : "Alfa Romeo",
"Car" : "Alfa Romeo Guilia 2.0T Super Automatic Petrol Sedan RWD",
}, {
"Brand" : "Alfa Romeo",
"Car" : "Alfa Romeo Stelvio 2.0 Turbo Super Automatic Petrol SUV AWD",
}, {
"Brand" : "Alfa Romeo",
"Car" : "Alfa Romeo Stelvio 2.0 Turbo First Edition Automatic Petrol SUV AWD",
}, {
"Brand" : "Alfa Romeo",
"Car" : "Alfa Romeo 4C 1750Tbi N/A TCT Petrol Coupe RWD",
}]
上面的父级是`CarList2'
在我的颤振代码中,我必须使用以下内容来检索品牌:
final dbRef = FirebaseDatabase.instance.reference().child('CarList2');
void CreateNewDeal(String selectedcar) async{
await dbRef.orderByChild('Car').equalTo(selectedcar).once().then((DataSnapshot snap) {
print('length - ${snap.value.length}');
List<dynamic> brand = [];
// Code for Index 0 and index 1
snap.value.forEach((v1) {
brand.add(v1);
if(snap.value.length == 1 && brand[0]['Brand'] != null){
selectedbrand = brand[0]['Brand'];
print('brand index0 - ${brand[0]['Brand']}');
}
else if(snap.value.length == 2){
print('brand index 1 - ${snap.value[1]['Brand']}');
}
});
/**
following code gets the brand for index 1-->
*/
Map<dynamic,dynamic> values = snap.value;
values.forEach((key, v2) {
selectedbrand = v2['Brand'];
print('Brand index 2>:(${v2['Brand']})');
});
});
}catch(e){
print(e.toString());
}
}
在上面,如果选择索引 1 的汽车,我不能与索引 1 同时运行索引 0 和索引 2,因为代码将在索引 0 或 2 上返回空值,然后永远不会进入代码对于索引 1。
我还为孩子们获得了可变长度的快照,如下所示:
索引 0 = 长度 1 索引 1 - 长度 2 索引 2 及以上 = 长度 1
是我做错了什么还是我打算以不同的方式阅读这篇文章?
【问题讨论】:
-
在使用 Firebase 实时数据库时,强烈建议不要使用数字索引,而是使用其内置的
push()方法生成的键。虽然它们最初可能看起来更冗长和棘手,但它们将防止这个问题和许多其他问题。见firebase.googleblog.com/2014/04/… -
@FrankvanPuffelen,谢谢你,我会尝试改变这个,但这个列表是基于手动捕获的信息,而不是由我的应用程序生成的。在这种情况下,它是按制造商列出的汽车列表。这些是真实世界定义的。还有其他替代方法吗?
-
这是两个选项:1) 像您目前所做的那样使用类似数组的索引,2) 按照博文的建议使用 Firebase 推送 ID。
标签: flutter dart firebase-realtime-database