【问题标题】:StreamProvider not updating ListStreamProvider 不更新列表
【发布时间】:2020-01-07 08:36:52
【问题描述】:

我有一个 StreamController 应该更新 List 但它没有发生:

class LocationService {
    StreamController<List<bg.Geofence>> geofencesController = StreamController<List<bg.Geofence>>();

    updateGeofences(geofences) {
        logger.i('listing geofences $geofences');
        geofencesController.add(List.from(list));
    }
}

当我致电updateGeofences 时,我在日志中发现了许多地理围栏。 但是小部件没有重建!

这是我的供应商设置:

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MultiProvider(
        providers: [
          StreamProvider<List<bg.Geofence>>.value(
              updateShouldNotify: (_, __) {
                logger.i('updateShouldNotify, $_, $__');
                return true;
              },
              initialData: List<bg.Geofence>(),
              stream: LocationService().geofencesController.stream)
        ],
        child: MaterialApp()
     );
  }
}

当我直接从我的服务中收听时

geofencesController.stream.listen((onData) {
  logger.i('Got eem! $onData');
});

流发出新数据... 但不是在 StreamProvider 中:updateShouldNotify 从未被调用(我尝试过这个answer's 解决方案,但没有运气)

以下是我查看数据的方式:

class GPSView extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    List<bg.Geofence> geofences = Provider.of<List<bg.Geofence>>(context);

但是这个列表仍然是空的。

我有另一个 StreamController 和一个简单的 Map,它工作得很好。怎么了?

【问题讨论】:

  • 这可能不是问题,但你不应该在这里使用.value 构造函数。请参阅this Creating a ChangeNotifier 部分也适用于 StreamProvider
  • LocationService().geofencesController.stream 创建一个新的LocationService 和一个新的geofencesController 所以你使用两个不同的控制器
  • 嗨@RémiRousselet!我遵循medium.com/flutter-community/… 教程,该教程使用 GetIt() 将 LocationService 保持为单例。不是吗? locator.registerLazySingleton(() =&gt; LocationService());
  • 所以,你让我走上了正轨!它与 StreamProvider 无关。我只需要拨打locator&lt;LocationService&gt;() 而不是LocationService()。干杯! ??????
  • 将提供程序与 get_it 一起使用不是一个好主意。它们是并发的。

标签: flutter dart flutter-provider


【解决方案1】:

感谢@pskink 和@RémiRoussele cmets,我设法解决了我的问题:

我正在通过调用LocationService().geofencesController.stream 重新创建LocationService

我将代码更新为

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MultiProvider(
        providers: [
          StreamProvider<List<bg.Geofence>>(
            builder: (_) => locator<LocationService>().geofencesController,
            initialData: List<bg.Geofence>(),
          ),
        ],
        child: MaterialApp();
  }
}

现在一切正常!干杯!

【讨论】:

    猜你喜欢
    • 2020-04-15
    • 2019-12-13
    • 2021-12-14
    • 2020-10-26
    • 1970-01-01
    • 2021-03-01
    • 2020-11-06
    • 2021-07-02
    • 2021-02-07
    相关资源
    最近更新 更多