Paramclasses Academy - Blog

Tutorials Details

←
Post 23 of 40
→

How to Store App Preferences and Local Data in Flutter

How to Store App Preferences and Local Data in Flutter

November 2, 2026

❖ How to Store App Preferences and Local Data in Flutter

❖ Welcome to Param Classes!

Imagine opening a mobile application, entering your name and selecting Dark Mode. After closing and reopening the application, you expect your name and theme preference to remain saved.

But how does an application remember this information?

The answer is Local Data Storage.

Local storage allows a Flutter application to save information directly on the user's device. This information can be accessed again when the application is reopened.

For example, applications may save:

  • Username and user preferences.

  • Dark Mode or Light Mode settings.

  • Language selection.

  • Onboarding completion status.

  • Login preferences.

  • Simple application settings.

Flutter developers can use different storage solutions depending on the type and amount of data.

In this tutorial by Param Classes, you will learn how to store app preferences using SharedPreferences and build practical examples step by step.

✦ 1. What Is Local Data Storage in Flutter?

Local data storage means saving information on the device instead of sending every piece of information to a remote server.

For example, suppose you create a Notes application. Users may want to save their notes and access them later, even after closing the app.

Local storage helps make this possible.

Benefits of local storage:

  1. Data can remain available after the application closes.

  2. Some information can be accessed without an internet connection.

  3. Applications can remember user preferences.

  4. It reduces the need to request the same settings repeatedly.

  5. It can improve the user experience.

However, not every type of information should be stored using the same storage method. Choose a storage solution according to your data requirements.

✦ 2. Different Ways to Store Data in Flutter

Flutter applications can use several local storage approaches.

Storage Method Common Use
SharedPreferences Simple preferences and settings
SQLite Structured relational data
Hive Local database storage
Files Documents, images and other files
Secure Storage Sensitive values such as tokens

In this tutorial, our main focus is SharedPreferences.

You will explore SQLite and Hive in more detail in the next database tutorial.

✦ 3. What Is SharedPreferences?

SharedPreferences is a Flutter package used to store small amounts of simple key-value data on a device.

For example:

Key Value
username Aman
isDarkMode true
language English
isFirstTime false

Here, each piece of information is stored using a key and its corresponding value.

SharedPreferences supports common data types such as:

  • String

  • int

  • double

  • bool

  • List of String

Important: SharedPreferences is designed for simple preferences, not large databases or complex relational information. It should not be used to store passwords or other highly sensitive information.

Official package: https://pub.dev/packages/shared_preferences

✦ 4. Install SharedPreferences in Flutter

Before using SharedPreferences, you need to install its package.

Step 1: Open your Flutter project

Open your project in Android Studio or VS Code.

Step 2: Open the terminal

Run the following command:

flutter pub add shared_preferences

This command adds the package to your Flutter project.

Step 3: Import the package

Add this import wherever you need to use SharedPreferences:

import 'package:shared_preferences/shared_preferences.dart';

Now you can save and retrieve simple local preferences.

✦ 5. Save Data Using SharedPreferences

Let's start with a simple example.

Suppose you want to save a user's name in the application.

SharedPreferences provides methods such as setString() to save string values.

Example:

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

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

Explanation:

  • SharedPreferences.getInstance() obtains the preferences instance.

  • await waits for the asynchronous operation.

  • setString() saves a string value.

  • username is the key.

  • Aman is the value.

You can also save other supported data types.

Save an Integer:

await prefs.setInt('age', 22);

Save a Boolean:

await prefs.setBool('isLoggedIn', true);

Save a Double:

await prefs.setDouble('price', 99.50);

Save a List of Strings:

await prefs.setStringList(
  'courses',
  ['Flutter', 'Dart', 'Python'],
);

These methods allow you to save simple application preferences.

✦ 6. Retrieve Data from SharedPreferences

Saving information is only one part of local storage. You also need to retrieve that information when required.

For example, you can read the saved username using getString().

Example:

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

  String? username = prefs.getString('username');

  print(username);
}

Explanation:

  • getInstance() obtains the preferences instance.

  • getString() reads the saved value.

  • username stores the retrieved result.

  • The value is nullable because the key may not exist.

You can retrieve other supported values too.

int? age = prefs.getInt('age');

bool? isLoggedIn = prefs.getBool('isLoggedIn');

double? price = prefs.getDouble('price');

List<String>? courses = prefs.getStringList('courses');

If a key does not exist, these methods return null.

✦ 7. Delete Stored Data

Sometimes users need to remove saved preferences.

SharedPreferences provides different methods for deleting data.

Remove a Specific Key:

final prefs = await SharedPreferences.getInstance();

await prefs.remove('username');

Clear All Preferences:

final prefs = await SharedPreferences.getInstance();

await prefs.clear();

Be careful when using clear(), because it removes all preferences in that storage instance. Do not use it if you only want to delete one particular setting.

✦ 8. Practical Project: Save and Display Username

Now let's build a simple Flutter application that allows users to:

  • Enter their name.

  • Save their name locally.

  • Retrieve the saved name.

  • Display the saved name on the screen.

  • Delete the saved name.

✦ Complete Code

Create a file named main.dart and add the following code:

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 const MaterialApp(
      debugShowCheckedModeBanner: false,
      home: HomePage(),
    );
  }
}

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

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {

  final TextEditingController nameController =
      TextEditingController();

  String savedName = "No Name Saved";

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

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

    await prefs.setString(
      'username',
      nameController.text.trim(),
    );

    await loadName();

    nameController.clear();
  }

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

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

    if (!mounted) return;

    setState(() {
      savedName = name ?? "No Name Saved";
    });
  }

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

    await prefs.remove('username');

    if (!mounted) return;

    setState(() {
      savedName = "No Name Saved";
    });
  }

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("Local Storage Example"),
      ),

      body: Padding(
        padding: const EdgeInsets.all(20),

        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [

            TextField(
              controller: nameController,
              decoration: const InputDecoration(
                labelText: "Enter Your Name",
                border: OutlineInputBorder(),
              ),
            ),

            const SizedBox(height: 20),

            ElevatedButton(
              onPressed: saveName,
              child: const Text("Save Name"),
            ),

            const SizedBox(height: 15),

            Text(
              "Saved Name: $savedName",
              style: const TextStyle(
                fontSize: 20,
                fontWeight: FontWeight.bold,
              ),
            ),

            const SizedBox(height: 20),

            ElevatedButton(
              onPressed: loadName,
              child: const Text("Load Name"),
            ),

            ElevatedButton(
              onPressed: deleteName,
              child: const Text("Delete Name"),
            ),

          ],
        ),
      ),
    );
  }
}

✦ How Does This Project Work?

1. TextEditingController

The controller captures the name entered by the user.

2. initState()

Flutter calls initState() when the State object is initialized. Here, it loads the previously saved name.

3. saveName()

This function saves the entered name using setString().

4. loadName()

This function retrieves the saved name using getString() and updates the screen with setState().

5. deleteName()

This function removes the username from local storage.

6. dispose()

The controller is disposed of when the screen is removed.

✦ Test Your Application

  1. Run the Flutter application.

  2. Enter your name in the text field.

  3. Tap Save Name.

  4. Close and reopen the application.

  5. Check whether your saved name appears.

  6. Tap Delete Name to remove the saved value.

This demonstrates how simple preferences can remain available between application launches.

✦ 9. Practical Example: Save Dark Mode Preference

Many mobile applications allow users to select Light Mode or Dark Mode.

You can store this preference locally so the application remembers the user's selection.

Example:

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

  await prefs.setBool('darkMode', isDarkMode);
}

To retrieve the saved preference:

Future<bool> getTheme() async {
  final prefs = await SharedPreferences.getInstance();

  return prefs.getBool('darkMode') ?? false;
}

Here:

  • true means Dark Mode is enabled.

  • false means Light Mode is enabled.

  • If no preference exists, the application uses Light Mode by default.

You can connect this value to your application's theme settings.

✦ 10. Important Things to Remember

When using local storage in real-world applications, follow these practices:

  1. Use SharedPreferences for simple data: Store settings, preferences and small values.

  2. Use asynchronous methods: SharedPreferences operations use Future, so use async and await.

  3. Handle missing values: A saved key may not exist, so provide suitable default values.

  4. Avoid sensitive information: Do not store passwords or confidential data in ordinary preferences.

  5. Choose the correct storage solution: Use SQLite or another database when your application needs structured records.

  6. Test persistence: Close and reopen your application to verify that saved preferences remain available.

  7. Handle errors appropriately: Consider error handling for important storage operations.

✦ 11. Common Mistakes Beginners Should Avoid

1. Forgetting await

SharedPreferences methods are asynchronous. Use await when you need to wait for an operation to finish.

2. Using the Wrong Data Type

Use setString() for text, setInt() for integers and setBool() for Boolean values.

3. Forgetting Default Values

A preference may not exist the first time an application opens. Use fallback values such as:

bool isDarkMode = prefs.getBool('darkMode') ?? false;

4. Using SharedPreferences as a Database

SharedPreferences is not designed for storing large collections of complex records.

5. Forgetting to Update the UI

After retrieving data, use an appropriate state management approach, such as setState(), to display updated values.

✦ 12. Practice Tasks for Beginners

After completing this tutorial, try these exercises:

  • Save a user's name and display it after restarting the application.

  • Save a mobile application's Dark Mode preference.

  • Store a language selection such as English or Hindi.

  • Save whether the onboarding screen has been completed.

  • Create a simple settings screen with Save and Reset buttons.

  • Build a small application that remembers the user's preferred theme.

These tasks will help you understand how local preferences work in Flutter.

❖ Conclusion

Local data storage is an important part of Flutter application development. It allows applications to remember user preferences and simple information even after the application is closed.

In this tutorial, you learned what local storage is, explored different storage methods, installed SharedPreferences, saved and retrieved values, removed stored data and created a practical username storage application.

You also learned how to save a Dark Mode preference and why SharedPreferences should be used for simple key-value data rather than complex database records.

At Param Classes, we believe beginners learn programming best through practical examples and real-world projects. Keep practicing these concepts and gradually explore more advanced local database solutions.

Learn Today, Grow Tomorrow with Param Classes!

←
Post 23 of 40
→