StreamProvider returns null 即使数据是从 FireStore 中获取的

StreamProvider returns null even though the data is fetched from FireStore

我正在尝试流式传输从 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'),
    );
}


  

下面的代码只有 returns 'Loading...' 文本,因为 _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),
    );
}

下面的代码处理从 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 列表就好了。