从Firestore获取某些文档数据以填充下拉列表

时间:2020-04-18 13:36:19

标签: flutter dart google-cloud-firestore

我正在尝试使用Firestore数据填充下拉列表。我想尽可能轻巧地执行此操作,而不进行任何流生成器排序或其他不需要的操作。 我在服务中创建了可重用的调用以存储到Firestore,以仅获取所需的文档

  Future<List<Map<String, dynamic>>> getCollections<T>(String path) async {
    final data = await Firestore.instance.collection(path).getDocuments();
    final result = data.documents.map((doc) => doc.data).toList();
    return result;
  }

我在数据库中使用它来获取特定路径下的集合

  Future<List<Map<String, dynamic>>> brandStream() =>
      _service.getCollections('all_brands');

然后在我的按钮中暂时调用它以打印数据

           onPressed: () async {
              final database =
                  Provider.of<Database>(context, listen: false);
              var r = await database.brandStream();
              print(r);
            }

这一切都可以,但是显然它也可以提取我不感兴趣的数据。我只需要从每个集合中获取名称和图像url,但是我可以获得该集合中的所有其他内容。最好的方法是什么?我不知道如何将数据添加到仅包含名称和URL的模型类中(如上一个问题)Return List of <T> from firestore collections

1 个答案:

答案 0 :(得分:1)

您必须像这样在服务文件中包含T构建器

  Future<List<T>> getCollections<T>(
      {String path,
      @required
          T builder(Map<String, dynamic> data, String documentID)}) async {
    final data = await Firestore.instance.collection(path).getDocuments();
    final result =
        data.documents.map((doc) => builder(doc.data, doc.documentID)).toList();
    return result;
  }

然后在数据库文件中使用构建器将数据添加到模型类中

  @override
  Future<List<Brand>> brandStream() => _service.getCollections(
      path: 'tool_bank', builder: (data, id) => Brand.fromMap(data, id));

您的模型类应该在哪里

class Brand {
  String logo, name, bid;
  Brand({this.logo, this.name, this.bid}); 

  factory Brand.fromMap(Map<String, dynamic> brandData, String documentID) {
    if (brandData == null) {
      return null;
    }
    final String logo = brandData['logo'];
    final String name = brandData['logo'];

    return Brand(logo: logo, name: name, bid: documentID);
  }
}

然后您可以使用与使用

相同的方式