Understanding Shared Preferences in Flutter with Practical Examples
Published: 2024-06-04 12:05:29

#What are Shared Preferences?
Shared Preferences in Flutter allow you to store key-value pairs of primitive data types. This storage method is perfect for saving small amounts of data, such as user settings or application preferences, that need to persist across sessions but do not require the overhead of a database.

#Why Use Shared Preferences?
Using shared preferences in your Flutter app comes with several advantages:

- Simplicity: Easy to implement and use.
- No Database Needed: Avoids the complexity and resource usage of a full database.
- Efficiency: Ideal for storing small amounts of data.
- Persistence: Data remains available across app restarts.

##Getting Started with Shared Preferences in Flutter
First, add the **shared_preferences** package to your **_pubspec.yaml_** file:

```
dependencies:
  flutter:
    sdk: flutter
  shared_preferences: ^2.0.6

```
Run **_flutter pub get_** to install the package.

##Basic Usage
**Import the Package**
To use shared preferences, start by importing the package:

```dart
import 'package:shared_preferences/shared_preferences.dart';
```
**Saving Data**
Here's a simple function to save a string value:

```dart
Future<void> saveStringValue(String key, String value) async {
  final prefs = await SharedPreferences.getInstance();
  await prefs.setString(key, value);
}
```
**Retrieving Data**
To retrieve the stored string value, use:

```dart
Future<String?> getStringValue(String key) async {
  final prefs = await SharedPreferences.getInstance();
  return prefs.getString(key);
}
```

Here is a complete example of code for storing and retrieving data from Shared Preferences:
```dart
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Shared Preferences Demo',
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  String _key = "key";
  String _value = "value";

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

  // Function to load saved value from SharedPreferences
  void _loadSavedValue() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    setState(() {
      _value = prefs.getString(_key) ?? ""; // Using ?? "" to handle null case
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Shared Preferences Demo"),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text("Value: $_value"),
            TextField(
              decoration: InputDecoration(
                hintText: "Enter value",
              ),
              onChanged: (value) {
                setState(() {
                  _value = value;
                });
              },
            ),
            RaisedButton(
              child: Text("Save"),
              onPressed: () {
                _saveValue();
              },
            ),
          ],
        ),
      ),
    );
  }

  // Function to save value to SharedPreferences
  void _saveValue() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    await prefs.setString(_key, _value);
  }
}
```