Shared Preferences in Flutter is a simple way to store small amounts of data persistently. This is particularly useful for storing user preferences, settings, or any other small data that needs to be retained across app launches.

Key Concepts

  1. SharedPreferences Package: A Flutter plugin that provides a persistent storage mechanism for simple data.
  2. Key-Value Storage: Data is stored as key-value pairs, similar to a dictionary.
  3. Data Types Supported: Shared Preferences support basic data types like int, double, bool, String, and List<String>.

Setting Up Shared Preferences

Step 1: Add Dependency

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.

Step 2: Import the Package

Import the shared_preferences package in your Dart file:

import 'package:shared_preferences/shared_preferences.dart';

Using Shared Preferences

Saving Data

To save data, you need to get an instance of SharedPreferences and then use the appropriate setter method.

Future<void> saveData() async {
  final prefs = await SharedPreferences.getInstance();
  await prefs.setInt('counter', 10);
  await prefs.setString('username', 'JohnDoe');
  await prefs.setBool('isLoggedIn', true);
}

Reading Data

To read data, you also need to get an instance of SharedPreferences and then use the appropriate getter method.

Future<void> readData() async {
  final prefs = await SharedPreferences.getInstance();
  int counter = prefs.getInt('counter') ?? 0;
  String username = prefs.getString('username') ?? 'Guest';
  bool isLoggedIn = prefs.getBool('isLoggedIn') ?? false;

  print('Counter: $counter');
  print('Username: $username');
  print('Is Logged In: $isLoggedIn');
}

Removing Data

To remove data, use the remove method with the key of the data you want to delete.

Future<void> removeData() async {
  final prefs = await SharedPreferences.getInstance();
  await prefs.remove('counter');
}

Practical Example

Let's create a simple Flutter app that uses Shared Preferences to store and retrieve a counter value.

Step 1: Create a New Flutter Project

flutter create shared_preferences_example
cd shared_preferences_example

Step 2: Update pubspec.yaml

Add the shared_preferences dependency:

dependencies:
  flutter:
    sdk: flutter
  shared_preferences: ^2.0.6

Step 3: Update main.dart

Replace the content of lib/main.dart with the following code:

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(
      home: CounterScreen(),
    );
  }
}

class CounterScreen extends StatefulWidget {
  @override
  _CounterScreenState createState() => _CounterScreenState();
}

class _CounterScreenState extends State<CounterScreen> {
  int _counter = 0;

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

  // Load counter value from SharedPreferences
  Future<void> _loadCounter() async {
    final prefs = await SharedPreferences.getInstance();
    setState(() {
      _counter = prefs.getInt('counter') ?? 0;
    });
  }

  // Increment counter and save to SharedPreferences
  Future<void> _incrementCounter() async {
    final prefs = await SharedPreferences.getInstance();
    setState(() {
      _counter++;
    });
    await prefs.setInt('counter', _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(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headline4,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
}

Step 4: Run the App

Run the app using flutter run. You should see a counter that increments each time you press the floating action button. The counter value is saved using Shared Preferences and will persist across app launches.

Exercises

Exercise 1: Save User Preferences

Create a form that allows users to save their name and email. Use Shared Preferences to persist this data.

Solution:

  1. Add text fields for name and email.
  2. Save the data using Shared Preferences when the user submits the form.
  3. Load the data when the form is initialized.

Exercise 2: Theme Preference

Add a toggle switch to enable dark mode. Save the user's preference using Shared Preferences and apply the theme accordingly.

Solution:

  1. Add a switch to toggle between light and dark themes.
  2. Save the theme preference using Shared Preferences.
  3. Load the theme preference when the app starts and apply the theme.

Common Mistakes and Tips

  • Forgetting to await: Always use await when calling methods on SharedPreferences to ensure the data is saved or loaded correctly.
  • Null Safety: Always provide a default value when reading data to handle cases where the key might not exist.

Conclusion

In this section, you learned how to use Shared Preferences in Flutter to store and retrieve small amounts of data persistently. This is a powerful tool for saving user settings, preferences, and other small pieces of data that need to be retained across app launches. In the next section, we will explore file storage for handling larger amounts of data.

Flutter Development Course

Module 1: Introduction to Flutter

Module 2: Dart Programming Basics

Module 3: Flutter Widgets

Module 4: State Management

Module 5: Navigation and Routing

Module 6: Networking and APIs

Module 7: Persistence and Storage

Module 8: Advanced Flutter Concepts

Module 9: Testing and Debugging

Module 10: Deployment and Maintenance

Module 11: Flutter for Web and Desktop

© Copyright 2024. All rights reserved