Search code examples
flutterdartfirebase-realtime-databaselocationgeofire

How can I use GeoFire plugin to update my location in background


I am using this plugin to update my location in firebase. When the app is in foreground everything works perfectly but as soon as my app goes in background then the location update service stops,I tried using didChangeAppLifecycleState but I can't seem to get it to work, This is my implementaion so far..

class HomeTabPage extends StatefulWidget {


    @override
    _HomeTabPageState createState() => _HomeTabPageState();
}

class _HomeTabPageState extends State < HomeTabPage >
    with AutomaticKeepAliveClientMixin, WidgetsBindingObserver {
        @override
        void initState() {
            super.initState();
            WidgetsBinding.instance.addObserver(this);
        }

        @override
        void dispose() {
            super.dispose();
            WidgetsBinding.instance.removeObserver(this);
        }

        @override
        void didChangeAppLifecycleState(AppLifecycleState state) async {
            super.didChangeAppLifecycleState(state);
            if (state == AppLifecycleState.inactive ||
                state == AppLifecycleState.detached) return;
            final isBackground = state == AppLifecycleState.paused;

            if (isBackground) {

                print("### paused");
                StreamSubscription < Position > backgroundStreamSubscription =
                    Geolocator.getPositionStream().listen((Position position) {
                        initPositionPoint = position;
                        Geofire.setLocation(
                            currentFirebaseUser.uid, position.latitude, position.longitude);

                    });

            }
        }

Solution

  • From Github issues #53 and #444 of the flutter-geolocator repo it seems that it doesn't support background location tracking. It seems that some folks have been using background_locator as an alternative, so you might want to look at that.