DEV Community

sk00l
sk00l

Posted on

Understanding Shared Preferences in Flutter with Practical Examples

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

Enter fullscreen mode Exit fullscreen mode

Run flutter pub get to install the package.

Basic Usage

Import the Package
To use shared preferences, start by importing the package:

import 'package:shared_preferences/shared_preferences.dart';
Enter fullscreen mode Exit fullscreen mode

Saving Data
Here's a simple function to save a string value:

Future<void> saveStringValue(String key, String value) async {
  final prefs = await SharedPreferences.getInstance();
  await prefs.setString(key, value);
}
Enter fullscreen mode Exit fullscreen mode

Retrieving Data
To retrieve the stored string value, use:

Future<String?> getStringValue(String key) async {
  final prefs = await SharedPreferences.getInstance();
  return prefs.getString(key);
}
Enter fullscreen mode Exit fullscreen mode

Here is a complete example of code for storing and retrieving data from Shared Preferences:

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);
  }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (5)

Collapse
 
hendrikras profile image
Hendrik Ras

Hey friend, nice post! 👋

did you know you can get syntax highlighting with your codeblocks in markdown? Simply put the language of your choice after the code block declaration, like:

import 'package:shared_preferences/shared_preferences.dart';
Enter fullscreen mode Exit fullscreen mode

Here's a formatting guide in case you need some help troubleshooting. Best of luck and thanks again for sharing this post!

Collapse
 
sk00l profile image
sk00l

Thank you for the tip 🙌🙌

Collapse
 
drumkillerpeter profile image
Peter Bk
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

class AppPreferences {
  AppPreferences() {
    _init();
  }

  Future<void> _init() async {
    sharedPreferences = await SharedPreferences.getInstance();
  }

  SharedPreferences? sharedPreferences;
  static const String _themeMode = 'themeMode';

  Future<void> setThemeMode(ThemeMode themeMode) async {
    await sharedPreferences?.setString(_themeMode, themeMode.name);
  }

  ThemeMode getThemeMode() {
    final themeModeString = sharedPreferences?.getString(_themeMode);
    if (themeModeString == null) return _getSystemTheme();
    return ThemeMode.values.firstWhere((e) => e.name == themeModeString);
  }

  ThemeMode _getSystemTheme() {
    if (WidgetsBinding.instance.platformDispatcher.platformBrightness ==
        Brightness.dark) return ThemeMode.dark;
    return ThemeMode.light;
  }
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
pulo0 profile image
Bartek Skrzypek

Great article! Really helped me out 🙌

Collapse
 
drumkillerpeter profile image
Peter Bk

Great Post. 🔥