0

how to store starting and ending time of a timer using shared preference in flutter and when i close the app and reopen app should start from ending timer time

if anyone knows anything regarding this issue please share

  • Does this answer your question? [How to save to local storage using Flutter?](https://stackoverflow.com/questions/41369633/how-to-save-to-local-storage-using-flutter) – Hossein Vejdani Feb 03 '23 at 13:35

1 Answers1

0

By using WidgetsBindingObserver you can listen to your application state.

class MyPage extends StatefulWidget {
  @override
  _MyPageState createState() => _MyPageState();
}

class _MyPageState extends State<MyPage> 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) {
    super.didChangeAppLifecycleState(state);
     
    // Here you will get your application state like resumed, inactive, paused, detached


    // when the application will close `detached` state will come, and store the latest timer data in your shared preferences
    
    if(state == AppLifecycleState.detached){
   
    // store last timer data into shared preferences 
    
   }

   print('Current state = $state');
  }

  @override
  Widget build(BuildContext context) => Scaffold();
}

and when your application starts :

  1. Get the data from Shared preferences and Start the timer from there
  2. Do this thing after initializing the shared preferences in main.dart or in your root widget.
Sanket Patel
  • 202
  • 5
  • This is What I used but it's not what i want....i made a clock and want to store start and end time in sharedpreference. so when i ll kill the app and reopen it should get the end time from sharedpreference and should start from that point i killed the app...i hope you got my point – Jahan Zaib PJ Feb 04 '23 at 14:43