我在模型类中遇到问题,无法将实时 Firebase 数据库中的数据提取到列表中,但收到 null。通过下面的图片进一步说明:
这是一个模型类:
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 的类:
class Body extends StatefulWidget {
@override
_BodyState createState() => _BodyState();
}
class _BodyState extends State<Body> {
final urlImage =
'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSPlqk-tNmFTjT7q_edAjaYLU5qf2cFUM9vfrweUbqnS_58LqF7AMp67KVdslIubuzy9b4&usqp=CAU';
final _database = FirebaseDatabase.instance.reference().child('kjobhee');
List<Seller> _sellerList;
StreamSubscription<Event> _onTodoAddedSubscription;
Query _query;
@override
void initState() {
super.initState();
_activateListeners();
}
void _activateListeners() {
_query = _database.child('seller');
_onTodoAddedSubscription = _query.onValue.listen(onEntryAdded);
}
onEntryAdded(Event event) {
setState(() {
_sellerList.add(Seller.fromSnapshot(event.snapshot));
print(_sellerList);
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: kPrimaryColor,
),
drawer: NavigationDrawer(),
body: RefreshIndicator(
onRefresh: () => _buildBuyerProfile(),
child: _sellerList.length > 0
? ListView.builder(
shrinkWrap: true,
itemCount: _sellerList.length,
itemBuilder: (BuildContext context, int index) {
String key = _sellerList[index].key;
String address = _sellerList[index].address;
int blockByAdmin = _sellerList[index].blockByAdmin;
String businessType = _sellerList[index].businessType;
String description = _sellerList[index].description;
int completeOrders = _sellerList[index].completeOrders;
String fcm = _sellerList[index].fcm;
String joinTimeStamp = _sellerList[index].joinTimeStamp;
double lat = _sellerList[index].lat;
double lng = _sellerList[index].lng;
String name = _sellerList[index].name;
String onlineStatus = _sellerList[index].onlineStatus;
String picUrl = _sellerList[index].picUrl;
int rating = _sellerList[index].rating;
String uuid = _sellerList[index].uuid;
print(key +
'/' +
address +
'/' +
blockByAdmin.toString() +
'/' +
businessType +
'/' +
description +
'/' +
completeOrders.toString() +
'/' +
fcm +
'/' +
joinTimeStamp +
'/' +
lat.toString() +
'/' +
lng.toString() +
'/' +
name +
'/' +
onlineStatus +
'/' +
picUrl +
'/' +
rating.toString() +
'/' +
uuid);
return _buildBuyerProfile();
})
: Center(
child: CircularProgressIndicator(),
),
),
);
}
我将非常感谢任何用户的帮助。
这里您需要考虑一些事情:
您需要确保从 Firebase 获取数据,尝试在日志中打印它并检查您是否正在接收数据。
您需要管理您的用户界面,考虑到当屏幕首次加载时您的数据将不存在,这意味着您的变量 _sellerList 将为空。因此需要检查您的代码中缺少哪些内容。
如果您没有从 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 的帮助下显示该数据。
我认为你需要在模型中处理 null
像这样-
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"] ?? '';
也许你的问题会得到解决。我没试过,但你可以!