how to store data locally in flutter using shared preferences

How to Store Data Locally in Flutter Using SharedPreferences

Introduction

Most mobile applications need to save information. For example, a user may want an app to remember their preferred theme, language, or whether they have completed an introduction screen.

But what happens when the user closes the application?

If the information is not saved, it may disappear when the app restarts.

Flutter developers can use local storage to keep certain information on a device. One beginner-friendly option is SharedPreferences.

In this tutorial, you will learn what SharedPreferences is, how to install it, and how to save, read, update, and delete simple data in a Flutter application.

1. What Is Local Storage?

Local storage means saving information directly on a device instead of relying on an online server.

For example, a mobile application might save:

- The user's preferred theme.
- Language preferences.
- Whether a welcome screen has been completed.
- Simple application settings.
- A small number of user preferences.

Local storage can help an application remember certain choices even when the user closes and reopens it.

2. What Is SharedPreferences?

SharedPreferences is a Flutter plugin that provides access to simple key-value storage on supported platforms.

A key-value pair contains a name and its associated value.

For example:

- Key: "username"
- Value: "Chio"

Another example:

- Key: "darkMode"
- Value: "true"

SharedPreferences supports simple data types such as strings, integers, doubles, booleans, and lists of strings.

It is not designed to replace a database.

3. Install SharedPreferences

First, open your Flutter project.

Open the terminal and run:

flutter pub add shared_preferences

This command adds the package to your project.

You can also check the package documentation and current platform support on pub.dev.

4. Import the Package

Open your "main.dart" file and add:

import 'package:shared_preferences/shared_preferences.dart';

This allows your application to use the SharedPreferences API.

5. Save Data Using SharedPreferences

Let's create a simple example that saves a username.

Future<void> saveUsername(String name) async {
  final prefs = await SharedPreferences.getInstance();

  await prefs.setString('username', name);
}

Understanding the code

Step 1: "SharedPreferences.getInstance()" obtains the storage instance.

Step 2: "setString()" saves a string value.

Step 3: The key "username" identifies the information.

When you call this function with a name, the value is saved locally.

6. Read Saved Data

To retrieve information, use the appropriate getter.

For example:

Future<String?> getUsername() async {
  final prefs = await SharedPreferences.getInstance();

  return prefs.getString('username');
}

The function returns the saved username.

The return type is "String?" because the value might not exist yet.

You can also retrieve other supported types:

final age = prefs.getInt('age');

final darkMode = prefs.getBool('darkMode');

final rating = prefs.getDouble('rating');

final interests = prefs.getStringList('interests');

7. Update Existing Data

If you save another value using the same key, the previous value is replaced.

Example:

Future<void> updateUsername(String newName) async {
  final prefs = await SharedPreferences.getInstance();

  await prefs.setString('username', newName);
}

This changes the locally stored username.

8. Delete Saved Data

Sometimes users need to remove stored information.

To delete one value:

Future<void> deleteUsername() async {
  final prefs = await SharedPreferences.getInstance();

  await prefs.remove('username');
}

To clear all values stored by your application through this preferences instance:

Future<void> clearPreferences() async {
  final prefs = await SharedPreferences.getInstance();

  await prefs.clear();
}

Be careful with "clear()" because it removes all preferences in that store, not just one selected key.

9. Build a Simple Flutter App That Remembers a Username

Now let's put everything together.

Replace the contents of "lib/main.dart" with this example:

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

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

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Local Storage App',
      theme: ThemeData(
        colorSchemeSeed: Colors.blue,
        useMaterial3: true,
      ),
      home: const UsernamePage(),
    );
  }
}

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

  @override
  State<UsernamePage> createState() => _UsernamePageState();
}

class _UsernamePageState extends State<UsernamePage> {
  final TextEditingController controller =
      TextEditingController();

  String username = 'No username saved yet';

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

  Future<void> loadUsername() async {
    final prefs = await SharedPreferences.getInstance();

    final savedName = prefs.getString('username');

    if (!mounted) return;

    setState(() {
      username = savedName ?? 'No username saved yet';
    });
  }

  Future<void> saveUsername() async {
    final name = controller.text.trim();

    if (name.isEmpty) return;

    final prefs = await SharedPreferences.getInstance();

    await prefs.setString('username', name);

    if (!mounted) return;

    setState(() {
      username = name;
    });

    controller.clear();

    ScaffoldMessenger.of(context).showSnackBar(
      const SnackBar(
        content: Text('Username saved successfully!'),
      ),
    );
  }

  Future<void> deleteUsername() async {
    final prefs = await SharedPreferences.getInstance();

    await prefs.remove('username');

    if (!mounted) return;

    setState(() {
      username = 'No username saved yet';
    });
  }

  @override
  void dispose() {
    controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Local Storage Tutorial'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(20),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            const Icon(
              Icons.storage,
              size: 70,
              color: Colors.blue,
            ),
            const SizedBox(height: 20),
            const Text(
              'Saved Username:',
              style: TextStyle(fontSize: 18),
            ),
            const SizedBox(height: 10),
            Text(
              username,
              style: const TextStyle(
                fontSize: 22,
                fontWeight: FontWeight.bold,
              ),
            ),
            const SizedBox(height: 25),
            TextField(
              controller: controller,
              decoration: const InputDecoration(
                labelText: 'Enter your username',
                border: OutlineInputBorder(),
              ),
            ),
            const SizedBox(height: 15),
            SizedBox(
              width: double.infinity,
              child: ElevatedButton(
                onPressed: saveUsername,
                child: const Text('Save Username'),
              ),
            ),
            TextButton(
              onPressed: deleteUsername,
              child: const Text('Delete Saved Username'),
            ),
          ],
        ),
      ),
    );
  }
}

10. Test Your Application

After adding the code, run your Flutter application.

Try the following:

1. Enter a username.
2. Press Save Username.
3. Close the application.
4. Open it again.
5. Check whether the saved username appears.
6. Press Delete Saved Username to remove it.

The application should remember the username after restarting.

11. When Should You Use SharedPreferences?

SharedPreferences is suitable for small settings and simple preferences.

For example, you can use it to remember whether a user prefers dark mode.

However, it is not the right place for everything.

Avoid using it to store:

- Large collections of records.
- Complex database relationships.
- Large images or files.
- Passwords, authentication tokens, or other sensitive information without an appropriate secure-storage solution.

For sensitive information, consider a secure storage package. For larger or structured data, consider a local database such as SQLite or Isar.

Also remember that local storage is not automatically synchronized between a user's devices.

Conclusion

Local storage is an important part of Flutter application development.

SharedPreferences helps developers save small pieces of information directly on a user's device.

You have learned how to install the package, save information, read stored values, update data, and delete saved preferences.

Practise with this example before using local storage in larger projects.

CHIO BLOG App Development Academy: Learn to Code, Build Real Apps, and Create Your Future.

Comments

Popular posts from this blog

how to become an AI engineer in 2026

10 Blogging mistake bloginers should avoid

how to check waec result 2026