'How to Store Flutter default project counter app last value in local database?

Here is the Flutter default project.


class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);
  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.display1,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ), 
    );
  }
}

my question is :

When we are pressing the floating button It will increment right. So imagine that I incremented till number 20. And imagine there is a button called save, so when I pressed the save button how to save the last number (as I said number 20) in local db and show it when opened the app again, I know it is a vast question.



Solution 1:[1]

You can use shared_preferences for saving simple data:

Install and import first the library:

import 'package:shared_preferences/shared_preferences.dart';

Saving the counter

MaterialButton(
    child: Text("Save"),
    onPressed: () async {
        final prefs = await SharedPreferences.getInstance();

        // Save the counter 
        await prefs.setInt('counter', _counter);
    }
)

Retrieving and Setting the counter

class _MyHomePageState extends State<MyHomePage> {
    int _counter = 0;
  
    ...
    
    @override
    void initState() {
        super.initState();

        Future.delayed(Duration.zero, () async { 
            final prefs = await SharedPreferences.getInstance();

            setState(() {
                _counter = prefs.getInt('counter');
            });
        });
    }

    ...
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1