如何在Firebase数据获取函数中传入不同Model实现复用?
实现Firebase数据获取函数的复用(支持多Model)
完全不需要为每个Model单独编写函数,通过泛型结合Model的fromJson工厂方法就能实现函数复用,核心思路是把Model的解析逻辑从函数中抽离,作为参数传入。
泛型函数实现示例
假设你用的是Dart/Flutter,改造后的通用函数如下:
// 单条数据获取 Future<T> fetchSingleData<T>(String collectionPath, T Function(Map<String, dynamic>) fromJson) async { final snapshot = await FirebaseFirestore.instance.collection(collectionPath).get(); if (snapshot.docs.isEmpty) throw Exception("No data found"); return fromJson(snapshot.docs.first.data()); } // 列表数据获取(可选扩展) Future<List<T>> fetchListData<T>(String collectionPath, T Function(Map<String, dynamic>) fromJson) async { final snapshot = await FirebaseFirestore.instance.collection(collectionPath).get(); return snapshot.docs.map((doc) => fromJson(doc.data())).toList(); }
调用方式
针对不同Model,只需要传入对应的fromJson方法即可:
// 获取Model1类型数据 final model1 = await fetchSingleData('model1_collection', Model1.fromJson); // 获取Model2类型数据 final model2 = await fetchSingleData('model2_collection', Model2.fromJson); // 获取Model2列表 final model2List = await fetchListData('model2_collection', Model2.fromJson);
原理说明
泛型T让函数可以适配任意Model类型,而传入的fromJson参数负责把Firebase返回的Map数据转换成具体的Model实例,不管Model有多少不同字段,只要它实现了fromJson工厂方法,就能被这个通用函数处理。
内容的提问来源于stack exchange,提问作者t3nsa
相关产品推荐
相关产品推荐

