如何在Flutter应用程序中从Firestore导入Map数据?

tyg4sfes  于 2023-05-23  发布在  Flutter
关注(0)|答案(1)|浏览(161)

我是Flutter的新手,我在将存储在firestore中的Map数据导入Flutter应用程序时遇到了一些问题。我成功地导入了一个数据和一些字符串变量。接下来的步骤是导入Map列表。我想要一个关于如何导入地址和产品列表的示例。
我有这个代码:

Future<void> getOrderDetails(String id) async {
final orderSnapshot = await FirebaseFirestore.instance
    .collection('orders')
    .where('Order id', isEqualTo: id)
    .get();
if (orderSnapshot.docs.isEmpty) {
  return;
}
final orderData = orderSnapshot.docs.first.data();
status = orderData['Status'];
print(status);
this.id = id;
print(this.id);
Timestamp t;
t = orderData['Date & Time'];
startDate = t.toDate();
print(startDate);
}

另外,firestore数据库看起来像这样:

afdcj2ne

afdcj2ne1#

您需要将从firestore检索到的数据转换为它们各自的数据结构类型。
例如:"Address"将是<String,dynamic>类型的Map
"Products"将是Map<String,dynamic>List,但转换为dynamic类型的List将正常工作。

Future<void> getOrderDetails(String id) async {
final orderSnapshot = await FirebaseFirestore.instance
    .collection('orders')
    .where('Order id', isEqualTo: id)
    .get();
if (orderSnapshot.docs.isEmpty) {
  return;
}
final orderData = orderSnapshot.docs.first.data();
status = orderData['Status'];
print(status);
this.id = id;
print(this.id);
Timestamp t;
t = orderData['Date & Time'];
startDate = t.toDate();
print(startDate);

//new code below
var addressMap = orderData['address'] as Map<String,dynamic>;
var buildingNum = addressMap['Building Number'];
print('building number: $buildingNum');

var productList = orderData['Products'] as List<dynamic>;
for(var productItemMap in productList){
  print('product name: ${productItemMap['name']}');
}
}

相关问题