Home > OS >  onDestroy or dispose in flutter
onDestroy or dispose in flutter

Time:01-19

I am developing a note app, and I want to save my note when I closed the app (when removing the app from recent apps). I tried dispose() method but it did not work. I tried :

@override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    print(state);
    final isDetached = state == AppLifecycleState.detached;}

but it did not work too. it does not print detached status, just it prints AppLifecycleState.paused AppLifecycleState.inactive AppLifecycleState.resume

so what should I do here!!

CodePudding user response:

Your code should look something like this if you're observing the app lifecycle state:

class AppLifecycleReactor extends StatefulWidget {
  const AppLifecycleReactor({ Key? key }) : super(key: key);

  @override
  State<AppLifecycleReactor> createState() => _AppLifecycleReactorState();
}

class _AppLifecycleReactorState extends State<AppLifecycleReactor> with WidgetsBindingObserver {
  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance!.addObserver(this);
  }

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

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    print(state);
  }

  @override
  Widget build(BuildContext context) {
    return Widgets;
  }
}

to summarise:

  • with WidgetsBindingObserver after extends State
  • WidgetsBinding.instance!.addObserver(this); in initstate
  • WidgetsBinding.instance!.removeObserver(this); in dispose

For more info check: https://api.flutter.dev/flutter/widgets/WidgetsBindingObserver-class.html

CodePudding user response:

dispose() function is only visible in StatefulWidget

void main() {
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  final AppRouter _appRouter = AppRouter();

  @override
  Widget build(BuildContext context) {
    return BlocProvider<CounterCubit>(
      create: (context) => CounterCubit(),
      child: MaterialApp(
        title: 'Flutter Demo',
        theme: ThemeData(
          primarySwatch: Colors.blue,
          visualDensity: VisualDensity.adaptivePlatformDensity,
        ),
        onGenerateRoute: _appRouter.onGenerateRoute,
      ),
    );
  }

  @override
  void dispose() {
    super.dispose();
    // dispose your code here
  }
}

CodePudding user response:

You can always use shared preferences in that case. Share preferences are used to save data in your local storage and the implementation is also very simple. and don't worry it won't make your app laggy or slow. It works very smoothly

https://pub.dev/packages/shared_preferences

do upvote if helpful

  •  Tags:  
  • Related