Flutter从Firebase Cloud Firestore返回完整阵列 [英] Flutter return full arrays from Firebase Cloud Firestore
问题描述
9月2日最新
即使有赏金,我对此也没有太大的吸引力,所以我将尝试问一个更简单,更具体的问题.
I am not getting much traction with this, even with a bounty, so I will try and ask a simpler and more specific question.
因此,我已按照Doug的以下建议对数据库进行了重组,因为我无法以其他方式在Firebase中引用数组.所以现在我有了一个数组映射,而不仅仅是数组.像这样:
So I have reorganised the database in line with Doug's suggestions below, as I cannot otherwise reference the arrays in any way in firebase. So now I have a map of arrays, rather than just arrays. Like so:
ObjectsList > CarsMap (Map)
- sh899873jsa (Array)
0 "Toyota"
1 "Supra"
2 "1996"
3 "$4990"
- hasd823j399 (Array)
0 "Toyota"
1 "Corolla"
2 "2014"
3 "$11990"
- nelaoiwi283 (Array)
0 "Ford"
1 "Territory"
2 "2018"
3 "$35000"
但是我不知道如何实际使用此结构,因为我以前从未见过.我现在遇到第一个错误,这是弗兰克在下面的回答中提供给我的代码,我将其转换为:
But I don't know how to actually use this structure, as I have never seen this before. I am getting the first error now with the code provided to me by Frank in his answer below, which I have converted to:
final DocumentReference documents = await Firestore.instance.collection('ObjectsList');
DocumentSnapshot snapshot = await documents.get();
Map<String, dynamic> data = snapshot.data;
var loadCarItems = [];
data.forEach((k,v) => {
values = List<String>.from(v as List<String>),
print(values),
if (values[0] == "Toyota") {
loadCarItems.add(values[0]),
},
});
setState(() {
CarItemsArray = loadCarItems;
});
但是由于我已更改为map>数组结构,因此在此行出现错误:
But since I have changed to a map>array structure I am getting an error on this line:
data.forEach((k,v) => {
values = List<String>.from(v as List<String>),
错误为:
Unhandled Exception: type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'List<String>' in type cast
很明显,现在结构已经更改,我需要更改此语法,但是我不知道如何更改,并且无法在线找到任何内容.
So clearly I need to change this syntax now the structure has changed, but I have no idea how, and can't find anything online.
以前的信息:
我正在尝试找到一种从Firebase返回整个数组的方法,以便随后可以处理内部数据.
I am trying to work out a way to return whole arrays from Firebase so that I can then process the data inside.
例如,我在数据库中有一个包含数组的文档,如下所示:
For example, I have a document in the database that contains arrays, like so:
ObjectsList > sh899873jsa
0 "Toyota"
1 "Supra"
2 "1996"
3 "$4990"
hasd823j399
0 "Toyota"
1 "Corolla"
2 "2014"
3 "$11990"
nelaoiwi283
0 "Ford"
1 "Territory"
2 "2018"
3 "$35000"
因此,对于每个数组,我在创建时都会生成一个随机密钥,这并不重要.我基本上只需要能够将所有数据作为单独的对象返回.理想地,例如,我希望能够返回"All Toyotas".那是这里的结局.
So for each array, I have generated a random key on creation, which is not important. I basically just need to be able to return all the data as separate objects. Ideally, I would like to be able to return "All Toyotas", for example. That's the end game here.
这是迄今为止我根据下面的弗兰克的建议生成的代码,弗兰克将我带入正确的道路.
Here is the code I have generated so far based on suggestions by Frank below who got me onto the right path.
从构建wdiget:
Container(
child: StreamBuilder(
stream: Firestore.instance.collection('cars').document('ObjectsList').snapshots(),
builder: (BuildContext context, AsyncSnapshot<DocumentSnapshot> snapshot) {
if (!snapshot.hasData) {
return LoadingAnimationBasic();
}
if (snapshot.data == null) {
return LoadingAnimationBasic();
} else {
return ListView(
shrinkWrap: true,
children: _buildListCards(snapshot),
);
}
},
),
),
_buildListCards函数经过简化,因此您可以看到它的工作原理:
The _buildListCards function, simplified so you can see how it works:
_buildStoresList(AsyncSnapshot<DocumentSnapshot> snapshot) {
return snapshot.data.data.values
.map((doc) => doc[0] == "Toyota" ? GestureDetector(
child: Container(
width: MediaQuery.of(context).size.width,
child: Card(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(0.0),
),
color: Colors.white70,
elevation: 10,
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Padding(
padding: const EdgeInsets.all(2.0),
child: ConstrainedBox(
constraints: BoxConstraints(
maxWidth: 120,
minWidth: 120,
maxHeight: 100,
minHeight: 100,
),
child: Image.network(
'some toyota picture URL',
fit: BoxFit.cover,
),
),
),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Container(
width: MediaQuery.of(context).size.width * 0.5,
child: Padding(
padding: const EdgeInsets.fromLTRB(10, 10, 0, 0),
child: Text(
doc[1],
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 18,
),
),
),
),
Container(
width: MediaQuery.of(context).size.width * 0.5,
child: Padding(
padding: const EdgeInsets.fromLTRB(5, 10, 0, 0),
child: Text(
doc[2],
style: TextStyle(
fontSize: 12,
),
),
),
),
],
),
Column(
children: <Widget>[
Padding(
padding: const EdgeInsets.fromLTRB(5, 40, 0, 0),
child: Text(
doc[3],
style: TextStyle(
fontSize: 14,
),
),
),
],
),
],
),
),
),
onTap: () {
futureTapHandlerHere();
},
) : SizedBox(), )
.toList();
}
因此,现在唯一剩下的就是能够从数据库中编辑/删除这些条目,而且我认为这必须依赖于创建它们时生成的唯一标识符.我看不到没有标识符怎么可能执行此功能,但是我不知道如何实际使用它或从数据库中返回它.
So the only thing that remains now is to be able to edit/delete these entries from the database, and I think this has to rely on the unique identifier generated when they are created. I can't see how else to possibly perform this functionality without the identifier, but I don't know how to actually use it, or return it from the database.
推荐答案
这不能通过问题中列出的格式来解决,而我正在尝试这种方式,因为另一个用户告诉我,我将无法删除单个数组,除非它们位于地图下.
This was not solved by doing it in the format listed in the question, and I was trying it this way as another user told me I would not be able to delete individual arrays unless they sat under a map.
这里的答案是上面的说法是不正确的,解决方案是完全放弃地图,只保留数组.我在这里所做的对我来说很有意义,就是使数组中的第一个对象成为唯一代码,因此我可以轻松地引用它,就像这样:
The answer here is that the above is not true, and the solution was to ditch the map altogether and just have the arrays. What I did here as it makes sense to me is to have the first object in the array be the unique code, so I can reference it easily, like so:
ObjectsList >
(document) - sh899873jsa (Array)
0 "sh899873jsa"
1 "Toyota"
2 "Supra"
3 "1996"
4 "$4990"
- hasd823j399 (Array)
0 "hasd823j399"
1 "Toyota"
2 "Corolla"
3 "2014"
4 "$11990"
- nelaoiwi283 (Array)
0 "nelaoiwi283"
1 "Ford"
2 "Territory"
3 "2018"
4 "$35000"
这些可以直接引用并轻松删除:
These can then be referenced directly and deleted easily:
_deleteMenuItem() async {
await deleteSelectedImages();
DocumentReference documentReference = Firestore.instance.collection('data').document('ObjectsList');
documentReference.updateData({
CarsMap[selectedItem][0]: FieldValue.delete(),
});
}
其中CarsMap是运行时加载的汽车对象数组,selectedItem是UI中从ListTiles中选择的项.因此,第一步是从Firebase获取所有数据,并将其填充到CarsMap数组中.第2步是从此数组构建ListTiles.步骤3是拥有一个onTap方法,该方法选择当前的ListTile,然后将该图块的索引存储到selectedItem中.
Where CarsMap is the loaded array of car objects at run time, and selectedItem is the item selected in the UI from the ListTiles. So step 1 was to grab all the data from Firebase and populate it into the CarsMap array. Step 2 was to build ListTiles from this array. Step 3 was to have an onTap method that selects the current ListTile, and then store the index of that tile into selectedItem.
这可以满足我的需要,用户现在可以根据需要填充和删除数据库中的数组.
This does what I need it to do, and users can now populate and remove arrays from my database as required.
这篇关于Flutter从Firebase Cloud Firestore返回完整阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!