Shared Preferences

How to use it ?

Using Shared Preferences in Flutter

What is Shared Preferences?

Shared Preferences is a simple key-value pair storage system in Flutter that allows you to persistently store small amounts of data locally on a device. It serves as a basic form of local storage, retaining data even when the application is terminated.

Basic Definition

In Flutter, Shared Preferences is commonly used for storing simple pieces of information, such as user preferences, authentication tokens, or any other data that needs to be maintained between app sessions.

Use Cases

1. User Preferences

Store and retrieve user-specific preferences, such as theme settings, language preferences, or notification settings.

2. Authentication

Persist authentication tokens locally to keep users logged in across app launches.

3. App Settings

Save and load application settings, allowing users to customize their app experience.

4. Quick Data Storage

For small, non-sensitive data that needs to be retained locally, like high scores, user progress, etc.

Caution: Use Cases and Limitations

While Shared Preferences is convenient for storing small amounts of data, it's important to note that it may not be the best choice for all scenarios. Avoid using Shared Preferences for sensitive data or large amounts of data, as it is not secure and may impact app performance.

Here's a sample code for you:

class _MyHomePageState extends State<MyHomePage> {
  final String key = 'counter';

  int _counter = 0;

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

  _loadCounter() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    setState(() {
      _counter = prefs.getInt(key) ?? 0;
    });
  }

  _incrementCounter() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    setState(() {
      _counter = (prefs.getInt(key) ?? 0) + 1;
      prefs.setInt(key, _counter);
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Shared Preferences Example'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'Counter Value:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headline4,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
}

Code Sample

To use Shared Preferences in a Flutter application, add the following dependency to your pubspec.yaml file:

dependencies:
  shared_preferences: ^2.0.9

Last updated