Storing Simple Data with Shared Preferences in Flutter

Storing Simple Data with Shared Preferences in Flutter

Storing Simple Data with Shared Preferences in Flutter

Storing Simple Data with Shared Preferences in Flutter

Summary
Summary
Summary
Summary

Shared preferences provide lightweight key-value storage in Flutter, ideal for settings like dark mode or login flags. This tutorial covers installation, basic CRUD methods, and a sample widget for saving preferences. Vibe Studio enhances this by enabling fast, visual Flutter development with persistent data capabilities.

Shared preferences provide lightweight key-value storage in Flutter, ideal for settings like dark mode or login flags. This tutorial covers installation, basic CRUD methods, and a sample widget for saving preferences. Vibe Studio enhances this by enabling fast, visual Flutter development with persistent data capabilities.

Shared preferences provide lightweight key-value storage in Flutter, ideal for settings like dark mode or login flags. This tutorial covers installation, basic CRUD methods, and a sample widget for saving preferences. Vibe Studio enhances this by enabling fast, visual Flutter development with persistent data capabilities.

Shared preferences provide lightweight key-value storage in Flutter, ideal for settings like dark mode or login flags. This tutorial covers installation, basic CRUD methods, and a sample widget for saving preferences. Vibe Studio enhances this by enabling fast, visual Flutter development with persistent data capabilities.

Key insights:
Key insights:
Key insights:
Key insights:
  • Platform Integration: Uses NSUserDefaults on iOS and SharedPreferences on Android for native support.

  • Data Types Supported: Store Booleans, strings, integers, and doubles asynchronously.

  • Sample Use Case: A dark mode toggle widget shows how to read and write values with UI feedback.

  • Key Management: Use static constants to avoid typos and ensure consistency.

  • Performance Tips: Cache SharedPreferences and limit usage to small, simple data.

  • Error Handling: Always handle nulls and defaults to avoid runtime issues.

Introduction

Shared preferences is a lightweight key-value storage API for Flutter, ideal for persisting simple data such as user settings, preferences, and small state details. Under the hood, it maps to NSUserDefaults on iOS and SharedPreferences on Android. This tutorial demonstrates how to integrate shared preferences into your Flutter app, covering setup, reading and writing values, and a practical widget example. By the end, you’ll have the basics to store Booleans, strings, integers, and doubles locally without a full database.

Installing the Plugin

Before you can read or write preferences, add the shared_preferences package to your project:

• Open pubspec.yaml

• Under dependencies, add:

shared_preferences: ^2.0.15

• Run flutter pub get

Import it where needed:

import 'package:shared_preferences/shared_preferences.dart';

That’s it. You now have access to the shared preferences API.

Reading and Writing Simple Data

SharedPreferences exposes methods to store primitive types. Every operation is asynchronous and returns a Future for write operations. Reads return the stored value or null if not set.

Key methods:

• setBool(key, value)

• getBool(key)

• setInt(key, value)

• getInt(key)

• setDouble(key, value)

• getDouble(key)

• setString(key, value)

• getString(key)

Example: Store and retrieve a username and a login flag.

// Save data
final prefs = await SharedPreferences.getInstance();
await prefs.setString('username', 'alice');
await prefs.setBool('loggedIn', true);

// Read data
final String? username = prefs.getString('username');
final bool isLoggedIn = prefs.getBool('loggedIn') ?? false;

Use consistent key names (ideally static constants) to avoid typos.

Practical Widget Example

Below is a Flutter widget that lets the user toggle a dark mode preference. It reads the saved value on startup and writes changes immediately.

class ThemeTogglePage extends StatefulWidget {
  @override
  _ThemeTogglePageState createState() => _ThemeTogglePageState();
}

class _ThemeTogglePageState extends State<ThemeTogglePage> {
  bool _isDarkMode = false;

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

  Future<void> _loadPreference() async {
    final prefs = await SharedPreferences.getInstance();
    setState(() {
      _isDarkMode = prefs.getBool('darkMode') ?? false;
    });
  }

  Future<void> _updatePreference(bool value) async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.setBool('darkMode', value);
    setState(() => _isDarkMode = value);
  }

  @override
  Widget build(BuildContext context) {
    return SwitchListTile(
      title: Text('Dark Mode'),
      value: _isDarkMode,
      onChanged: _updatePreference,
    );
  }
}

How it works:

  1. initState calls _loadPreference to read the stored Boolean.

  2. The SwitchListTile reflects the current preference.

  3. Toggling the switch calls _updatePreference, which writes the new value and updates UI.

Best Practices

• Always await SharedPreferences.getInstance() once per scope; consider caching the instance.

• Use const keys or static variables for preference names.

• Handle null or default values with ??.

• Keep preferences small—avoid storing complex objects or large datasets.

Vibe Studio

Vibe Studio, powered by Steve’s advanced AI agents, is a revolutionary no-code, conversational platform that empowers users to quickly and efficiently create full-stack Flutter applications integrated seamlessly with Firebase backend services. Ideal for solo founders, startups, and agile engineering teams, Vibe Studio allows users to visually manage and deploy Flutter apps, greatly accelerating the development process. The intuitive conversational interface simplifies complex development tasks, making app creation accessible even for non-coders.

Conclusion

You’ve now integrated shared preferences into a Flutter app, covered installation, basic read/write operations, and seen a real-world widget that persists theme settings. Shared preferences is perfect for simple key-value needs without introducing heavyweight storage solutions.

With shared preferences and tools like Vibe Studio, you can accelerate your Flutter projects, persist user data effortlessly, and focus on delivering great UX.

Persist Preferences the Easy Way

Persist Preferences the Easy Way

Persist Preferences the Easy Way

Persist Preferences the Easy Way

Use Vibe Studio to build Flutter apps with shared preferences—quickly and without boilerplate.

Use Vibe Studio to build Flutter apps with shared preferences—quickly and without boilerplate.

Use Vibe Studio to build Flutter apps with shared preferences—quickly and without boilerplate.

Use Vibe Studio to build Flutter apps with shared preferences—quickly and without boilerplate.

Other Insights

Other Insights

Other Insights

Other Insights

Join a growing community of builders today

Join a growing
community

of builders today

Join a growing

community

of builders today

© Steve • All Rights Reserved 2025

© Steve • All Rights Reserved 2025

© Steve • All Rights Reserved 2025

© Steve • All Rights Reserved 2025