简体   繁体   English

无法从 Firestore 数据库的解析列表中检索某些字段

[英]Cant retrieve certain fields from the parsed list of the Firestore database

I am building a restaurant app in which I have used Firestore as my backend.我正在构建一个使用 Firestore 作为后端的餐厅应用程序。 I have stored the details of the menu in a collection Menu and each menu item in specific documents.我已将菜单的详细信息存储在集合菜单中,并将每个菜单项存储在特定文档中。 Firstly, is that a good data model, or should I have the whole menu in the same document?首先,这是一个好的数据 model,还是我应该将整个菜单放在同一个文档中?

Secondly, the problem is while I retrieve the the collection and the docs, I am not being able to access some fields.其次,问题是当我检索集合和文档时,我无法访问某些字段。 If there are 4 documents and all of them contains the field 'Name' and data in the field.如果有 4 个文档并且它们都包含字段“名称”和字段中的数据。 But when I fetch the data, parse it inot the list and have the command Menu[index]['Name] only two of the names in the documents are displayed while the other two return null.但是当我获取数据时,将其解析为列表并使用命令 Menu[index]['Name] 仅显示文档中的两个名称,而其他两个返回 null。

class MenuController extends GetxController {
  final CollectionReference _menulsit =
      FirebaseFirestore.instance.collection('Menu');

  Future getmenu() async {
    List Menulist = [];
    try {
      await _menulsit.get().then((QuerySnapshot snapshot) {
        snapshot.docs.forEach((element) {
          Menulist.add(element.data());
        });
      });
      return Menulist;
    } catch (e) {
     
      return null;
    }
  }
}

While I parse it into a list and print the list, the data is retrieved and is printed in the console.当我将其解析为列表并打印列表时,数据被检索并打印在控制台中。 There is the field 'Name' printed on the console but when I try to access it from the list it returns null.控制台上打印了“名称”字段,但是当我尝试从列表中访问它时,它返回 null。 The same fields on some documents are returned but the same fields on some other documents are returned to be null.返回某些文档上的相同字段,但返回某些其他文档上的相同字段为 null。

I have used the list from the class, made a method, and provided a list here with the data retrieved.我使用了 class 中的列表,制作了一个方法,并在此处提供了一个包含检索到的数据的列表。 I need to use the data in a listview.seperated.我需要使用 listview.separated 中的数据。

class _FoodmenuState extends State<Foodmenu> {
  List menulist = [];
  @override
  void initState() {
    super.initState();
    fetchmenu();
  }

  Future fetchmenu() async {
    dynamic resultmenu = await MenuController().getmenu();
    if (resultmenu == null) {
      return Text('Unable to retrive data');
    } else {
      setState(() {
        menulist = resultmenu;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Column(children: [
      Container(
          height: 228,
          child: ListView.separated(
              scrollDirection: Axis.horizontal,
              itemBuilder: ((context, index) => _menucontent(index, menulist)),
              separatorBuilder: ((context, index) {
                return SizedBox(
                  width: 18,
                );
              }),
              itemCount: menulist.length))
    ]);
  }
}

While I print the list there is the field "Name" but I can't access it.当我打印列表时,有“名称”字段,但我无法访问它。

Print(menu)
I/flutter (31598): [{Name: Cheese Burger}, {Name : Buffalo Wings}, {Name : Pasta Bolognese }, {Name : Chicken MoMo}]

Print(menu[1])
I/flutter (31598): {Name : Buffalo Wings}

Print(menu[1]['Name']
I/flutter (31598): null

Its better to store each menu item in separate document as it would enable to fetch only some menu items based on some conditions.最好将每个菜单项存储在单独的文档中,因为它可以根据某些条件仅获取一些菜单项。

Regarding menu[1]['Name'] value printed as null:关于打印为 null 的 menu[1]['Name'] 值:

As Print(menu) is giving correct JSON response, I think there is extra space after Name word in firestore document.由于 Print(menu) 给出了正确的 JSON 响应,我认为在 Firestore 文档中 Name 字之后有额外的空格。 You might have added this data manually:)您可能已手动添加此数据:)

First of all you should consider defining data types as it would lower chances of error and provide better suggestion if data types are mentioned.首先,您应该考虑定义数据类型,因为如果提到数据类型,它将降低出错的机会并提供更好的建议。 Make a class of MenuItem and make menu items as it might help when you want to add any item in overall app.制作MenuItem的 class 并制作菜单项,因为当您想在整个应用程序中添加任何项目时它可能会有所帮助。 Below is a example to help you understand.下面是一个帮助你理解的例子。


class MenuItem {
  final String name;
  final int price;
  final String description;
  //you can add extra field here 
  MenuItem(
      {required this.name, required this.price, required this.description});
  MenuItem.fromJson(Map<String, dynamic> json)
      : name = json['name'],
        price = json['price'],
        description = json['description'];
}

Future getmenu() async {
  List<MenuItem> menulist = [];
  try {
    await _menulsit.get().then((QuerySnapshot snapshot) {
      snapshot.docs.forEach((element) {
        menulist.add(MenuItem.fromJson(element.data()));
      });
    });
    return menulist;
  } catch (e) {
    return menulist;
  }
}

Now if you want to access name you can try like this menulist[0].name beside this if you type menulist[0].现在,如果您想访问名称,您可以尝试在此菜单列表 [0].name旁边输入菜单列表 [0]。 it will give you suggestion whatever a menuItem can hold.无论 menuItem 可以容纳什么,它都会给你建议。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM