Firestore QuerySnapshot转List<Map>再转Item对象列表求助
将Firestore QuerySnapshot转为Item对象列表
需要把Firestore查询返回的QuerySnapshot转换为List<Map<String,dynamic>>,再进一步转为Item对象列表,现有代码如下:
现有Cubit代码
import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:htu_app/models/item.dart'; class categoryCubit extends Cubit<List<Item>> { categoryCubit() : super([]); Future<void> getItemsFromCategory({required String category}) async { QuerySnapshot docs = await FirebaseFirestore.instance .collection('items') .where('category', isEqualTo: category) .get(); } }
现有Item类代码
class Item { Item( {required this.name, required this.price, required this.category, required this.date, required this.pic}); String name; double price; String category; String date; String pic; factory Item.fromJson(Map<String, dynamic> json) => Item( name: json['name'], price: json['price'], category: json['category'], date: json['json'], // 此处存在笔误 pic: json['pic']); }
解决方案
首先修正Item类的fromJson方法笔误,将date: json['json']改为date: json['date'],同时添加类型断言确保类型安全。
然后在getItemsFromCategory方法中完成三步转换:提取文档数据为Map列表、转为Item对象列表、更新Cubit状态。
修正后的Item类
class Item { Item( {required this.name, required this.price, required this.category, required this.date, required this.pic}); String name; double price; String category; String date; String pic; factory Item.fromJson(Map<String, dynamic> json) => Item( name: json['name'] as String, price: (json['price'] as num).toDouble(), // 处理Firestore数字类型转double category: json['category'] as String, date: json['date'] as String, pic: json['pic'] as String); }
更新后的Cubit代码
import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:htu_app/models/item.dart'; class categoryCubit extends Cubit<List<Item>> { categoryCubit() : super([]); Future<void> getItemsFromCategory({required String category}) async { QuerySnapshot docs = await FirebaseFirestore.instance .collection('items') .where('category', isEqualTo: category) .get(); // 将QuerySnapshot转为Map列表 List<Map<String, dynamic>> itemsMapList = docs.docs .map((doc) => doc.data() as Map<String, dynamic>) .toList(); // 将Map列表转为Item对象列表 List<Item> itemsList = itemsMapList .map((itemMap) => Item.fromJson(itemMap)) .toList(); // 发射更新后的列表状态 emit(itemsList); } }
关键说明
- QuerySnapshot的
docs属性包含所有查询到的文档快照(QueryDocumentSnapshot); - 每个文档快照的
data()方法直接返回文档的键值对Map; - Firestore中存储的数字默认是
num类型,需要转为double匹配Item类的price字段; - 添加类型断言(
as String/as num)可以避免运行时类型错误。
内容的提问来源于stack exchange,提问作者Zain Erikat
相关产品推荐
相关产品推荐

