如何解决即使数据是从 FireStore 获取的,StreamProvider 也会返回 null
我正在尝试流式传输从 Firestore 获取的数据。它不起作用,因为 StreamProvider 似乎没有监听获取的数据,即使数据被获取并且可以记录在进程中。
Performing hot reload...
Syncing files to device AOSP on IA Emulator...
Reloaded 3 of 605 libraries in 407ms.
I/Flutter (22698): CvKGDloy8gsuLYIdjO9w
I/Flutter (22698): [822,930,1030,1145,1250,1355,1555,1640,1800,1900,2000,2100,2130,2200]
下面的代码启动了StreamProvider。
//app.dart
if (snapshot.hasData) {
final _streamBusSchedules = ApiService().streamBusSchedules();
return StreamProvider<List<BusSchedule>>.value(
initialData: [BusSchedule.initialData()],value: _streamBusSchedules,catchError: (_,__) => null,child: HomePage(title: 'My Amazing App'),);
}
下面的代码只返回“正在加载...”文本,因为 _busSchedules 为空。
//home_page.dart
Widget _buildList(BuildContext context) {
var _busSchedules = Provider.of<List<BusSchedule>>(context);
if (_busSchedules != null) {
return ListView.builder(
itemExtent: 40.0,itemCount: _busSchedules.length,itemBuilder: (context,index) =>
_buildListItem(context,_busSchedules[index]),);
}
return Center(
child: Text('Loading...'),);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(title),),body: _buildList(context),);
}
//api.dart
class ApiService {
final FirebaseFirestore _db = FirebaseFirestore.instance;
Stream<List<BusSchedule>> streamBusSchedules() async* {
var ref = _db.collection('bus-schedules');
await for (final snapshot in ref.snapshots()) {
yield snapshot.docs.map((doc) => BusSchedule.fromMap(doc)).toList();
}
}
}
解决方法
这是因为 BusSchedule.fromMap(doc) 因为不符合类型要求只返回了一次。
class BusSchedule {
final String id;
final String name;
final List<int> weekdays;
显然,List<int>
对数字数组不满意。将其更改为仅 List
,流提供程序返回 BusSchedule 列表就好了。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。