flutter_background_service plugin not listning to firebaseFirestore latest updates on app start

33 Views Asked by At

Context I am Working on a project and in it i am using firebase stream to listen to database updates and update some data in the database and also there is a bool variable in database lets call it "allowed", i am using flutter background services package (https://pub.dev/packages/flutter_background_service) to run some code in foreground mode even if user closes application from recent apps.

Desired Behaviour When application starts start firebase document listner to listen to changes on allowed and if allowed is true then start writing data to database and if at any document update allowed is false close the application and if the application is running in the foreground mode end background service as well.

Problem When application is reopened after getting exited last time because of allowed variable being false and now when allowed variable is no longer false firebase document listener still shows allowed variable to be false and exit the application.

Things Tried i ran the same code listener code in a normal function which is called in screen init state method and it works fine but when writing same code in onStart method of flutter background service package initilization it doesn't work as expected.

Additional info about code i don't know if will help but here but in void main function right after WidgetsFlutterBinding initialization i'm initializing firebase and using await before it and then initializing and configuring background services and background services onStart method throws no firebase app initialized error and as a work around to this i just again initialize firebaseapp in onStart method and it dosen't throw error anymore at least but i dont know if its the right thing to do search online but could'nt find much. thx

Dummy program in dummy application code i'm just listening to updates and not writing any changes to the database. (For Whole Dummy application code https://codefile.io/f/IHfqmxoymv)

// main function
void main()async {

  WidgetsFlutterBinding.ensureInitialized();

  // initilizing firebase app for first time and waiting for it to finish
  await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform);

  // initilizing background services
  await initilizedForgroundServices();
  
  runApp(home());
}


// onStart function passed when configuring services
pragma('vm:entry-point')
void onStart(ServiceInstance service)async{

  await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform);
  late StreamSubscription<Position> locationStream;
  late StreamSubscription<DocumentSnapshot<Map<String, dynamic>>> firebaseDocumentListner;
  bool isLocationStreamRunning = false;
  bool isFirebaseDocListenerStreamRunning = false;

  
  if(service is AndroidServiceInstance){
    service.on("stopService").listen((event) {
      if(isLocationStreamRunning){
        isLocationStreamRunning=false;
        isFirebaseDocListenerStreamRunning=false;
        locationStream.cancel();
        firebaseDocumentListner.cancel();
        service.stopSelf();
      }
    });
  }

  
  if(!isFirebaseDocListenerStreamRunning){
    isFirebaseDocListenerStreamRunning=true;
    firebaseDocumentListner =await FirebaseFirestore.instance.collection("Stops").doc("TEST").snapshots().listen((document) async {
      print("New Firebase Update....");

      // runs only if stream is not already running and Driving is allowed
      if(!isLocationStreamRunning && document.get("DrivingAllowed")){
        isLocationStreamRunning=true;
        locationStream = startGeoLocatorStream();
        if(service is AndroidServiceInstance){
          if (await service.isForegroundService()){
          service.setForegroundNotificationInfo(
            title: "Tracking On ", 
            content: "tracking....",
            );
          }
        }
      }
      
      // runs when Driving Allowed is false in snapshot and stream is running 
      else if(isLocationStreamRunning && !document.get("DrivingAllowed")) {
        isLocationStreamRunning=false;
        locationStream.cancel();
        firebaseDocumentListner.cancel();
        service.stopSelf();
      }

      // runs if driving allowed is false resuting in program being exitted
      else{
        service.stopSelf();
      }

      
      print(document.get("DrivingAllowed"));

    });
  }

  
}


0

There are 0 best solutions below