0

I want to run some tasks when I closed application using flutter, This tasks are some functions to delete data from firebase when the app is closing (detached)

I used WorkManager and didChangeAppLifecycleState, it is work when state == AppLifecycleState.pused but not work if the state == AppLifecycleState.detached. what I can to do that, thank you

const task = 'test';
void callbackDispatcher() {
  Workmanager().executeTask((task, inputData) async {
    await Firebase.initializeApp();
    currentFirebaseUser = fAuth.currentUser;
 FirebaseFirestore.instance.collection('locations').doc(currentFirebaseUser!.uid).delete();
    print(currentFirebaseUser!.uid+"++++++++++++++++++");
    return Future.value(true);
  });
}
void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Workmanager().initialize(
    callbackDispatcher,
    isInDebugMode: true,
  );
  AwesomeNotifications().initialize(null, [
    NotificationChannel(
      channelKey: 'test_channel',
      channelName: 'Test Notification',
      channelDescription: 'Notifications for basic testing',
    )
  ]);
  await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform);
  runApp(
    MyApp(
      child: ChangeNotifierProvider(
        create: (context) => AppInfo(),
        child: GetMaterialApp(
          initialBinding: ControllerBindings(),
          title: 'Drivers App',
          theme: ThemeData(
            primarySwatch: Colors.blue,
          ),
          home: const AuthGate(),
          debugShowCheckedModeBanner: false,
        ),
      ),
    ),
  );
}

class MyApp extends StatefulWidget {
  final Widget? child;
 const MyApp({this.child});
  static void restartApp(BuildContext context) {
    context.findAncestorStateOfType<_MyAppState>()!.restartApp();
  }
  @override
  _MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> with WidgetsBindingObserver{
  Key key = UniqueKey();
  void restartApp() {
    setState(() {
      key = UniqueKey();
    });
  }
  @override
  void initState() {
    WidgetsBinding.instance.addObserver(this);
    super.initState();
  }
  @override
  void dispose() {
  WidgetsBinding.instance.removeObserver(this);
    // TODO: implement dispose
    super.dispose();
  }
  @override
  void didChangeAppLifecycleState(AppLifecycleState state) async {
    if (state == AppLifecycleState.detached) {
      var uniqueName = DateTime.now().second.toString();
      await Workmanager().registerOneOffTask(uniqueName, task);
      print("------------------------");
    }
  }
  @override
  Widget build(BuildContext context) {
    return KeyedSubtree(
      key: key,
      child: widget.child!,
    );
  }
}
Oualid
  • 1
  • 2

0 Answers0