【发布时间】: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构造函数。请参阅thisCreating a ChangeNotifier部分也适用于 StreamProvider -
LocationService().geofencesController.stream创建一个新的LocationService和一个新的geofencesController所以你使用两个不同的控制器 -
嗨@RémiRousselet!我遵循medium.com/flutter-community/… 教程,该教程使用 GetIt() 将 LocationService 保持为单例。不是吗?
locator.registerLazySingleton(() => LocationService()); -
所以,你让我走上了正轨!它与 StreamProvider 无关。我只需要拨打
locator<LocationService>()而不是LocationService()。干杯! ?????? -
将提供程序与 get_it 一起使用不是一个好主意。它们是并发的。
标签: flutter dart flutter-provider