【问题标题】:Flutter: Unable to fetch data from model to list无法从模型中获取数据到颤振列表中
【发布时间】:2023-03-28 01:48:02
【问题描述】:

我在模型类中遇到问题,用于从实时 Firebase 数据库中获取数据到列表中但接收到 null。通过以下图片进一步说明:

这是要获取数据的图像 [1]:https://i.stack.imgur.com/Uyt34.png
这是一个模型类

 class Seller {

      var key;

  String address,businessType,description,fcm,joinTimeStamp,name,onlineStatus,picUrl,uuid;
  int blockByAdmin,completeOrders,rating;
  double lat;
  double lng;
  
  Seller(
      this.address,
      this.blockByAdmin,
      this.businessType,
      this.description,
      this.completeOrders,
      this.fcm,
      this.joinTimeStamp,
      this.lat,
      this.lng,
      this.name,
      this.onlineStatus,
      this.picUrl,
      this.rating,
      this.uuid);

  Seller.fromSnapshot(DataSnapshot snapshot)
      : key = snapshot.value,
        address = snapshot.value["address"],
        blockByAdmin = snapshot.value["blockByAdmin"],
        businessType = snapshot.value["businessType"],
        description = snapshot.value["description"],
        completeOrders = snapshot.value["completeOrders"],
        fcm = snapshot.value["fcm"],
        joinTimeStamp = snapshot.value["joinTimeStamp"],
        lat = snapshot.value["lat"],
        lng = snapshot.value["lng"],
        name = snapshot.value["name"],
        onlineStatus = snapshot.value["onlineStatus"],
        picUrl = snapshot.value["picUrl"],
        rating = snapshot.value["rating"],
        uuid = snapshot.value["uuid"];

  toJson() {
    return {
      'address': address,
      'blockByAdmin': blockByAdmin,
      'businessType': businessType,
      'description': description,
      'completeOrders': completeOrders,
      'fcm': fcm,
      'joinTimeStamp': joinTimeStamp,
      'lat': lat,
      'lng': lng,
      'name': name,
      'onlineStatus': onlineStatus,
      'picUrl': picUrl,
      'rating': rating,
      'uuid': uuid,
    };
  }
}

这是一个我们使用模型类并在列表长度处获取 null 的类。

类主体扩展 StatefulWidget { // const Body({Key?key}) : super(key: key); @覆盖 _BodyState createState() => _BodyState(); } 类 _BodyState 扩展状态 { 最终的 urlImage = 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSPlqk-tNmFTjT7q_edAjaYLU5qf2cFUM9vfrweUbqnS_58LqF7AMp67KVdslIubuzy9b4&usqp=CAU'; final _database = FirebaseDatabase.instance.reference().child('kjobhee'); 列出_sellerList; StreamSubscription _onTodoAddedSubscription; 查询_查询; @覆盖 无效初始化状态(){ super.initState(); _activateListeners(); } 无效_activateListeners(){ //_sellerList = new List(); _query = _database.child('卖家'); _onTodoAddedSubscription = _query.onValue.listen(onEntryAdded); } onEntryAdded(事件事件){ 设置状态((){ _sellerList.add(Seller.fromSnapshot(event.snapshot)); 打印(_sellerList); }); } @覆盖 小部件构建(BuildContext 上下文){ 返回脚手架( 应用栏:应用栏( 背景颜色:kPrimaryColor, ), 抽屉:导航抽屉(), 正文:刷新指示器( onRefresh: () => _buildBuyerProfile(), 孩子:_sellerList.length > 0 ? ListView.builder( 收缩包装:是的, itemCount:_sellerList.length, itemBuilder: (BuildContext context, int index) { 字符串键 = _sellerList[index].key; 字符串地址 = _sellerList[index].address; int blockByAdmin = _sellerList[index].blockByAdmin; String businessType = _sellerList[index].businessType; 字符串描述 = _sellerList[index].description; int completeOrders = _sellerList[index].completeOrders; 字符串 fcm = _sellerList[index].fcm; 字符串 joinTimeStamp = _sellerList[index].joinTimeStamp; 双纬度 = _sellerList[index].lat; 双 lng = _sellerList[index].lng; 字符串名称 = _sellerList[index].name; 字符串 onlineStatus = _sellerList[index].onlineStatus; 字符串 picUrl = _sellerList[index].picUrl; int rating = _sellerList[index].rating; 字符串 uuid = _sellerList[index].uuid; 打印(键 + '/' + 地址 + '/' + blockByAdmin.toString() + '/' + 业务类型 + '/' + 描述 + '/' + completeOrders.toString() + '/' + 厘米 + '/' + 加入时间戳+ '/' + lat.toString() + '/' + lng.toString() + '/' + 姓名 + '/' + 在线状态 + '/' + 图片网址 + '/' + rating.toString() + '/' + uuid); 返回 _buildBuyerProfile(); }) : 中心( 孩子:CircularProgressIndicator(), ), ), ); }

【问题讨论】:

  • 分享您的代码而不是图像以获得更好的理解。

标签: firebase flutter firebase-realtime-database


【解决方案1】:

您需要在这里考虑几件事:

  1. 您需要确保从 Firebase 获取数据,尝试将其打印到日志中并检查您是否正在接收数据。

  2. 您需要管理您的 UI,考虑到当屏幕首次加载时您的数据将不存在,这意味着您的变量 _sellerList 将为空。所以需要检查你的代码中缺少的那个。

  3. 如果您没有从 firebase 获取数据,但我认为配置已正确完成,那么您可以使用与我使用的代码相同的代码来获取数据:

    Future<void> fetchProducts() async {
    await FirebaseFirestore.instance
        .collection(FirebaseCollectionConst.productsCollection)
        .get()
        .then((QuerySnapshot productsData) {
      _products = [];
          productsData.docs.forEach((element) {
            _products.insert(0, Product(
                id: element.get('productId'),
                title: element.get('productTitle'),
                description: element.get('productDescription'),
                price: double.parse(element.get('price')),
                imageUrl: element.get('productImage'),
                brand: element.get('productBrand'),
                productCategoryName: element.get('productCategory'),
                quantity: int.parse(element.get('productQuality')),
                isFavourite: false,
                isPopular: true));
          });
    });
    

    }

在这里,我获取产品集合并收集到扩展 ChangeNotifier 类的类成员中,并在 Provider 的帮助下显示该数据。

【讨论】:

  • 谢谢,但你弄错了,我使用的是实时 firebase,而不是 fire-Store。 @Lavi Kashyap
猜你喜欢
  • 2020-11-17
  • 1970-01-01
  • 2021-12-22
  • 2021-12-16
  • 2021-07-27
  • 2021-03-26
  • 1970-01-01
  • 2020-12-19
  • 2021-06-05
相关资源
最近更新 更多