即使数据是从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'),
);
}


下面的代码只返回"正在加载…"text,因为_busSchedules为null。

//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),
);
}

下面的代码处理从firestore获取数据。

//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的列表。

最新更新