假设我在Dart中具有以下整数矩阵:
final List<List<int>> myMatrix = [
[1, 0, 0],
[0, 1, 0],
[0, 0, 1],
];
然后,我尝试将其存储在Cloud Firestore中,如下所示:
await Firestore.instance.collection("anyCollection").add({
"matrix" : myMatrix,
});
但是,一旦我运行上面的代码,模拟器就会崩溃,并且出现以下错误:
*** First throw call stack:
(
0 CoreFoundation 0x00007fff23c4f02e __exceptionPreprocess + 350
1 libobjc.A.dylib 0x00007fff50b97b20 objc_exception_throw + 48
2 Runner 0x000000010e83f8b5 _ZN8firebase9firestore4util16ObjcThrowHandlerENS1_13ExceptionTypeEPKcS4_iRKNSt3__112basic_stringIcNS5_11char_traitsIcEENS5_9allocatorIcEEEE + 581
3 Runner 0x000000010e83edf3 _ZN8firebase9firestore4util5ThrowENS1_13ExceptionTypeEPKcS4_iRKNSt3__112basic_stringIcNS5_11char_traitsIcEENS5_9allocatorIcEEEE + 67
4 Runner 0x000000010e890589 _ZN8firebase9firestore4util20ThrowInvalidArgumentIJEEEvPKcDpRKT_ + 57
5 Runner 0x000000010e959f65 -[FSTUserDataConverter parseData:context:] + 1045
6 Runner 0x000000010e<…>
Lost connection to device.
我正在文件中运行cloud_firestore: ^0.13.0+1
(当前为最新版本)pubspec.yaml
。运行flutter doctor
命令时,一切都很好。
我究竟做错了什么?甚至可以将矩阵存储在Firestore中吗?如果没有,我可以使用其他逻辑存储该数据吗?
我最终做了以下帮助程序,将矩阵转换为与Firestore兼容的地图:
class MatrixHelper {
// Creates a map that can be stored in Firebase from an int matrix.
static Map<String, dynamic> mapFromIntMatrix(List<List<int>> intMatrix) {
Map<String, Map<String, dynamic>> map = {};
int index = 0;
for (List<int> row in intMatrix) {
map.addEntries([MapEntry(index.toString(), {})]);
for (int value in row) {
map[index.toString()].addEntries(
[MapEntry(value.toString(), true)]
);
}
index += 1;
}
return map;
}
// Creates an int matrix from a dynamic map.
static List<List<int>> intMatrixFromMap(Map<dynamic, dynamic> dynamicMap) {
final map = Map<String, dynamic>.from(dynamicMap);
List<List<int>> matrix = [];
map.forEach((stringIndex, value) {
Map<String, dynamic> rowMap = Map<String, dynamic>.from(value);
List<int> row = [];
rowMap.forEach((stringNumber, boolean) {
row.add(int.parse(stringNumber));
});
matrix.add(row);
});
return matrix;
}
}
使用起来非常简单,要保存在Firestore中,就像这样:
final List<List<int>> myMatrix = [
[1, 0, 0],
[0, 1, 0],
[0, 0, 1],
];
await Firestore.instance.collection("anyCollection").add({
"matrix" : MatrixHelper.mapFromIntMatrix(myMatrix),
});
要从Firestore加载矩阵,方法如下:
// Loads the DocumentSnapshot:
final document = await Firestore.instance.collection("anyCollection").document("anyDocument").get();
// Retrieves the Matrix:
final List<List<int>> matrix = MatrixHelper.intMatrixFromMap(document.data["matrix"]);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句