Home > Software design >  How to save the value of counter each time I change it in flutter?
How to save the value of counter each time I change it in flutter?

Time:07-13

I have created a counter app in flutter. I pressed the increment button for 10 times. It was showing the counter value was 10 on the screen. But whenever i exit the app and reopen it shows the counter value is 0. Why is this happening? I want to save the counter value each time I change it. Can somebody solve my problem???

CodePudding user response:

I think that you should you shared_preferences library to write the value of counter to a persistent media. Add shared_preferences to your package.yaml. In your counter app override the method initState

var prefs;
@override
initState(){
    // Obtain shared preferences.
    prefs = await SharedPreferences.getInstance();
    _counter = prefs.getInt('counter');
}

and in increment counter function

// Save an integer value to 'counter' key.
await prefs.setInt('counter', _counter);

CodePudding user response:

You can save the on shared_preferences


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

  @override
  State<ParentWidget> createState() => _ParentWidgetState();
}

class _ParentWidgetState extends State<ParentWidget> {
  bool _isMuted = false;

  int counter = 0;

  SharedPreferences? preferences;

  Future<void> initStorage() async {
    preferences = await SharedPreferences.getInstance();
    // init 1st time 0
    int? savedData = preferences?.getInt("counter");
    if (savedData == null) {
      await preferences!.setInt("counter", counter);
    } else {
      counter = savedData;
    }
    setState(() {});
  }

  @override
  void initState() {
    super.initState();
    initStorage();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      floatingActionButton: FloatingActionButton(
        onPressed: () async {
          preferences?.setInt("counter", counter  = 1);
          setState(() {});
        },
      ),
      body: Column(
        children: [
          Text("${preferences?.getInt("counter")}"),

More about shared_preferences. Also you can check Hive and others local data storage.

  • Related