问题描述
我有一个StreamController,它应该更新一个 List
,但不会发生:
I have a StreamController which should update a List
but it doesn't happen:
class LocationService {
StreamController<List<bg.Geofence>> geofencesController = StreamController<List<bg.Geofence>>();
updateGeofences(geofences) {
logger.i('listing geofences $geofences');
geofencesController.add(List.from(list));
}
}
当我调用 updateGeofences
时,我在日志中得到了许多地理围栏.但是小部件不会重建!
When I call updateGeofences
I got many geofences in logs. But widget are not rebuilt!
这是我的提供商设置:
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()
);
}
}
当我直接从我的服务中收听时
When I listen directly from my service with
geofencesController.stream.listen((onData) {
logger.i('Got eem! $onData');
});
流发出新数据...但不在StreamProvider中:永远不会调用 updateShouldNotify
(我很幸运地尝试了 answer的解决方案)
The streams emits new data...But not in the StreamProvider: updateShouldNotify
is never called (I tried without luck this answer's solutions)
这是我查看数据的方式:
Here is how I get my data in view:
class GPSView extends StatelessWidget {
@override
Widget build(BuildContext context) {
List<bg.Geofence> geofences = Provider.of<List<bg.Geofence>>(context);
但是此列表仍然为空.
我还有另一个StreamController,它带有一个可以完美运行的简单Map.怎么了?
I have another StreamController with a simple Map which works perfectly. What's wrong?
推荐答案
感谢@pskink&@RémiRoussele评论我设法解决了这个问题:
So thanks to @pskink & @RémiRoussele comments I managed to fix my issue:
我正在通过调用 LocationService().geofencesController.stream
来重新创建 LocationService
.
I was recreating a LocationService
by calling LocationService().geofencesController.stream
.
我将代码更新为
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();
}
}
现在一切正常!干杯!
这篇关于StreamProvider未更新列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!