2

I am building a mobile app using flutter.

I would like to enable my stream provider when I log in and disable my stream when I log out.Also, I would like to keep streaming even if I leave the app and go to another app. The stream provides the phone location.

Right now , when I load the application it asks me right away if I want to enable the location service then when I enable it , it starts updating the phone location.

here is my code: main.dart

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [
        ChangeNotifierProvider.value(
          value: Auth(),
        ),
       
        StreamProvider.value(
          value: LocationService().locationStream,
        ),
      ],
      child: Consumer<Auth>(
        builder: (ctx, auth, _) => MaterialApp(
          title: 'deee',
          theme: ThemeData(
            primarySwatch: Colors.blue,
          ),
          home: auth.isAuth ? TabsScreen() : LoginPage(),
          initialRoute: "/",

          // onGenerate routes and unknown routes          "/": (ctx) => TabsScreen(),
          routes: {
           
          },
        ),
      ),
    );
  }
}

location_service.dart

import 'dart:async';
import 'dart:convert';
import 'package:location/location.dart';
import '../models/user_location.dart';
import '../providers/auth.dart';

import 'package:http/http.dart' as http;

class LocationService {
  // Keep track of current Location
  UserLocation _currentLocation;
  Location location = Location();
  Auth auth = Auth();
  int counter = 1;
  // Continuously emit location updates
  StreamController<UserLocation> _locationController =
      StreamController<UserLocation>.broadcast();

  LocationService() {
 
    location.requestPermission().then((granted) {
      if (granted == PermissionStatus.granted) {
        location.onLocationChanged.listen((locationData) async {
          if (locationData != null) {
            var firebaseId = auth.firebaseId;
            if (firebaseId != null) {
             
              try {
              
                final url =
                    'https://delivery-system-default-rtdb.firebaseio.com/Drivers/${firebaseId}.json';
                await http.patch(url,
                    body: jsonEncode({
                      'lat': locationData.latitude,
                      'lng': locationData.longitude,
                      'status': true
                    }));
              } catch (error) {
                print("error");
                print(error);
              }
            }

            counter++;

            _locationController.add(UserLocation(
              latitude: locationData.latitude,
              longitude: locationData.longitude,
            ));
          }
        });
      }
    });
  }

  Stream<UserLocation> get locationStream => _locationController.stream;

Thank you for your time and effort

castro
  • 37
  • 7
  • Does this answer your question? [How to create a Flutter background service that works also when app closed](https://stackoverflow.com/questions/62198049/how-to-create-a-flutter-background-service-that-works-also-when-app-closed) – Christian May 04 '21 at 18:25
  • 1
    @Christian this answers part of my question. but the main part when I want to enable location when I log in and disable location when I log out is not there . Thank you – castro May 04 '21 at 18:46
  • 1
    Hi @castro, could you find an answer to your question. I am facing the same problem. – Iman Jun 20 '22 at 19:45

0 Answers0