0
0
Fluttermobile~5 mins

SharedPreferences for key-value in Flutter

Choose your learning style9 modes available
Introduction

SharedPreferences lets your app save small pieces of data like settings or user choices. This data stays saved even if the app closes.

Save a user's theme choice (dark or light mode) so the app remembers it next time.
Store a user's login status to keep them logged in.
Keep track of simple counters or scores in a game.
Save user preferences like language or notifications on/off.
Syntax
Flutter
final prefs = await SharedPreferences.getInstance();
prefs.setString('key', 'value');
String? value = prefs.getString('key');
Use setX methods to save data, like setString, setInt, setBool.
Use getX methods to read data, like getString, getInt, getBool. It returns null if no value is saved.
Examples
Saves a boolean value to remember if the user is logged in.
Flutter
final prefs = await SharedPreferences.getInstance();
prefs.setBool('isLoggedIn', true);
Reads an integer value that counts how many times the app was opened.
Flutter
final prefs = await SharedPreferences.getInstance();
int? counter = prefs.getInt('launchCount');
Saves a username as a string.
Flutter
final prefs = await SharedPreferences.getInstance();
prefs.setString('username', 'Alice');
Sample App

This app shows a button and a counter. Each time you press the button, the counter increases and saves the number using SharedPreferences. When you restart the app, it remembers the last count.

Flutter
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

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

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  int _counter = 0;

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

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

  Future<void> _incrementCounter() async {
    final prefs = await SharedPreferences.getInstance();
    setState(() {
      _counter++;
    });
    await prefs.setInt('counter', _counter);
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: const Text('Counter with SharedPreferences')),
        body: Center(
          child: Text('You pressed the button $_counter times.', style: const TextStyle(fontSize: 20)),
        ),
        floatingActionButton: FloatingActionButton(
          onPressed: _incrementCounter,
          tooltip: 'Increment',
          child: const Icon(Icons.add),
        ),
      ),
    );
  }
}
OutputSuccess
Important Notes

SharedPreferences is good for small data only, not big files or complex data.

Always use await SharedPreferences.getInstance() before reading or writing.

Data saved is private to your app and persists across app launches.

Summary

SharedPreferences saves small key-value data that stays after app closes.

Use setX to save and getX to read values.

Great for saving user settings, counters, or simple flags.