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

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