+-
如何在Flutter中连续执行bloc事件?

我想在我的应用程序中连续跟踪用户的位置,因此,我想在我的主页面中连续执行getLocaiton bloc事件。因此,我想在我的主页上连续执行getLocaiton bloc事件。怎样才能做到这一点呢?

这是我的getLocation事件。

  GetLocationState get initialState => GetLocationState(saveUserCurrentLocation: initialPosition );

  Stream<GetLocationState> mapEventToState(LocationEvent event) async*{

    if (event is GetLocation){

      userLocation.getLocation().then((l){
        currentLatLng = LatLng(l.latitude, l.longitude);

      });


      yield GetLocationState(saveUserCurrentLocation: currentLatLng);


    }
  }

这是我的主页面

            initialCameraPosition:
                CameraPosition(target: initialPosition, zoom: 10),
            mapType: MapType.terrain,
            onMapCreated: _onMapCreated,
            myLocationEnabled: true,
          ),
          floatingActionButton: FloatingActionButton(
            onPressed: () {
              _locationBloc.add(GetLocation());
            },
          ),
        ),
      );
    });
  }

如何在后台连续运行代码,而不使用onPress事件?

1
投票

使用一个 Timer 里面 initState() (如果你的widget不是有状态的,那就把它变成有状态的).如果我理解你的问题,我认为你应该使用流来流转位置。

    Timer(Duration(seconds: 5), (){
      _locationBloc.add(GetLocation());
    });
-2
投票

如果我理解你的问题,我认为你应该使用流来流转位置。就像这个教程一样。

https:/medium.comflutter-communitybuild-a-location-service-in-flutter-367a1b212f7a。