StreamProvider not updating List

浪尽此生 提交于 2021-01-28 05:10:16

问题


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));
    }
}

When I call updateGeofences I got many geofences in logs. But widget are not rebuilt!

Here is my providers setup:

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');
});

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);

But this list remains empty.

I have another StreamController with a simple Map which works perfectly. What's wrong?


回答1:


So thanks to @pskink & @RémiRoussele comments I managed to fix my issue:

I was recreating a LocationService by calling LocationService().geofencesController.stream.

I updated my code to

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();
  }
}

And everything works now! Cheers!



来源:https://stackoverflow.com/questions/57788589/streamprovider-not-updating-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!