【问题标题】:Flutter Firebase Convert CollectionReference to ListFlutter Firebase 将 CollectionReference 转换为 List
【发布时间】:2021-10-01 05:48:20
【问题描述】:

如何将此集合引用转换为列表。

final _firestore = FirebaseFirestore.instance;

var sRef = _firestore.collection("vehicles1");

这个方法我试过了,没用;

List<String> sRefList = sRef;

我的子类别类

class SubCategory {
  String name;
  List<String> models;

  SubCategory({this.name, this.models});

  Map<String, dynamic> toMap() {
    return {
      'name': name,
      'models': models,
    };
  }

  factory SubCategory.fromMap(Map<String, dynamic> map) {
    return SubCategory(name: map['name'], models: map['models']);
  }
}

还有这个转换代码

List<SubCategory> _subcategories = [];

_firestore.collection("vehicles1").snapshots().map((event) {
      event.docs.forEach((element) {
        _subcategories.add(SubCategory.fromMap(element.data()));
      });
      return _subcategories.reversed.toList();
    });

print(_subcategories);

【问题讨论】:

    标签: firebase flutter arraylist collections converters


    【解决方案1】:
    FirebaseFirestore.instance
      .collection("colelction")
      .snapshots()
      .map((event) {
    List<SubCategory> _subcategories = [];
    event.docs.forEach((element) {
      _subcategories.add(SubCategory.fromMap(element.data()));
    });
    return _subcategories.reversed.toList();}),
    

    【讨论】:

    • List 中的 SubCategory 是什么
    【解决方案2】:
    class SubCountry {
    String countryID;
    String subCountryID;
    String subCountryName;
    SubCountry(
      {required this.countryID,
      required this.subCountryID,
      required this.subCountryName});
    
    Map<String, dynamic> toMap() {
    return {
      'country_id': countryID,
      'sub_country_id': subCountryID,
      'sub_country_name': subCountryName
    };
    }
    
    factory SubCountry.fromMap(Map<String, dynamic> map) {
    return SubCountry(
        countryID: map['country_id'],
        subCountryID: map['sub_country_id'],
        subCountryName: map['sub_country_name']);
    }
    }
    

    【讨论】:

    • 在我的数据库中我有字符串名称和列表模型,所以像这样实现这个代码
    • 类子类别 { 字符串名称;列出 模型;子类别({this.name, this.models}); Map toMap() { return { 'name': name, 'models': models, }; } factory SubCategory.fromMap(Map map) { return SubCategory(name: map['name'], models: map['models']); } }
    • 但是当我尝试打印子类别时列出它的返回 null
    猜你喜欢
    • 2021-01-21
    • 1970-01-01
    • 2021-05-27
    • 2020-04-16
    • 1970-01-01
    • 2021-11-17
    • 2019-02-16
    • 2020-08-03
    • 2021-11-11
    相关资源
    最近更新 更多