Understanding Shared Preferences in Flutter

What are Shared Preferences?

Shared Preferences is a lightweight data storage solution in Flutter, ideal for saving small pieces of data like user settings, login states, or simple preferences. It leverages key-value pairs to store data persistently on a device.

This is a mechanism that allows you to store and retrieve simple data on a device. This data is stored in key-value pairs and is persisted across app sessions. It is best suited for small, non-complex data such as:

  • User preferences (e.g., dark mode, language settings)
  • Session tokens
  • Simple flags (e.g., first-time app usage indicators)

Key Features of Shared Preferences

Lightweight

Best for storing simple key-value data; not suitable for large datasets or complex relationships.

Persistent

Data remains saved even if the app is closed or restarted.

Asynchronous API

Allows reading and writing data without blocking the UI thread.

Adding Shared Preferences to Your Flutter Project

To use Shared Preferences, add the shared_preferences package to your pubspec.yaml file:

dependencies:
  flutter:
    sdk: flutter
  shared_preferences: ^2.0.15

Then run:

flutter pub get

Using Shared Preferences

Here is a step-by-step guide to using Shared Preferences in your Flutter app.

1. Import the Package
import 'package:shared_preferences/shared_preferences.dart';
2. Saving Data

To save data, you need to use the set methods provided by SharedPreferences:

Future<void> saveData() async {
  final SharedPreferences prefs = await SharedPreferences.getInstance();
  await prefs.setString('username', 'JohnDoe');
  await prefs.setInt('age', 25);
  await prefs.setBool('isLoggedIn', true);
}
3. Retrieving Data

To retrieve data, use the corresponding get methods:

Future<void> loadData() async {
  final SharedPreferences prefs = await SharedPreferences.getInstance();
  String? username = prefs.getString('username');
  int? age = prefs.getInt('age');
  bool? isLoggedIn = prefs.getBool('isLoggedIn');
  print('Username: \$username');
  print('Age: \$age');
  print('Logged in: \$isLoggedIn');
}
4. Removing Data

To remove a specific key or clear all stored data:

Future<void> removeData() async {
  final SharedPreferences prefs = await SharedPreferences.getInstance();
  // Remove a specific key
  await prefs.remove('username');
  // Clear all data
  await prefs.clear();
}

Example: Persisting a Dark Mode Preference

Let’s walk through an example where we save and retrieve a user’s preference for dark mode.

Full Code Example
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
  bool _isDarkMode = false;
  @override
  void initState() {
    super.initState();
    _loadThemePreference();
  }
  Future<void> _loadThemePreference() async {
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    setState(() {
      _isDarkMode = prefs.getBool('darkMode') ?? false;
    });
  }
  Future<void> _toggleTheme(bool value) async {
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    setState(() {
      _isDarkMode = value;
      prefs.setBool('darkMode', _isDarkMode);
    });
  }
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: _isDarkMode ? ThemeData.dark() : ThemeData.light(),
      home: Scaffold(
        appBar: AppBar(title: Text('Shared Preferences Example')),
        body: Center(
          child: SwitchListTile(
            title: Text('Dark Mode'),
            value: _isDarkMode,
            onChanged: _toggleTheme,
          ),
        ),
      ),
    );
  }
}

In this example:

  • Dark Mode Preference: Stored using Shared Preferences.
  • State Management: The app’s theme toggles based on the saved preference.

When to Use Shared Preferences

Shared Preferences is great for small, simple data. However, it’s not suitable for:

Complex data

For large datasets, use a local database like sqflite or Hive.

Sensitive data

For highly sensitive information, consider using secure storage solutions such as the flutter_secure_storage package.

Final Thoughts

Shared Preferences is an easy and efficient way to persist small amounts of data in Flutter apps. It integrates seamlessly with most applications, making it an excellent choice for storing simple user preferences and states. You can use it to enhance user experience and maintain app states easily!

Enhance Your Flutter Skills

Stay tuned to our blog for more insights on Flutter development.

Ans Ali 3 February, 2025
Archive
Sign in to leave a comment
How to Replace a Word in Files, File Names, and Folder Names on Ubuntu