简单操作的问题 - 根据行的 ID 字段检索字符串字段不起作用(flutter + firebase)

问题描述 投票:0回答:1

我正在使用 flutter 开发一个学校项目,我必须根据 ID 检索产品的名称

功能如下

String retrieveItemName(String itemID) {
  
  // go through a firebase collection menuItems and retrieve the name field based on the ID argument
  String itemName = '';
  FirebaseFirestore.instance
      .collection('menuItems')
      .doc(itemID)
      .get()
      .then((DocumentSnapshot documentSnapshot) {
    if (documentSnapshot.exists) {
     ** itemName = documentSnapshot.data()!['name'];**
    }
  });
  return itemName;

看起来很简单 我在 firebase 中有一个名为 menuItems 的集合 该集合有一个 ID(从 firebase 自动生成)和一个名称。 我从其他地方检索 ID 并尝试将其映射到名称。

我遇到的问题是 没有为“Object”类型定义运算符“[]”。 尝试定义运算符“[]” 这指的是行:

** itemName = documentSnapshot.data()!['name'];**

关于如何处理这个问题有什么建议吗?

我不知所措,我尝试修改我的功能,但我不知道如何

flutter firebase function
1个回答
0
投票

看起来你只需要输入将对象转换为地图

解决方案1:

itemName = (documentSnapshot.data()! as Map<String, dynamic>)['name'];

解决方案2:

final Map <String, dynamic> item = documentSnapshot.data()!;
itemName = item['itemName'];

我希望这个解决方案可以帮助您解决您的问题。

© www.soinside.com 2019 - 2024. All rights reserved.