पाठ 20 / 25

Local Storage

shared_preferences, files and databases.

Choosing where to keep data

shared_preferences stores small key-value settings (theme choice, onboarding seen) using platform storage such as Android SharedPreferences and iOS NSUserDefaults; newer versions also offer SharedPreferencesAsync and SharedPreferencesWithCache APIs, so check the docs for your version. It is not encrypted - put tokens and secrets in flutter_secure_storage, which uses the Keychain and Android Keystore-backed encryption. For structured or larger data use SQLite through sqflite (raw SQL) or drift (type-safe queries and migrations, generated code), or other databases such as Isar or Hive. path_provider gives app document and cache directories for files.

Saving a setting

shared_preferences (classic API).

import 'package:shared_preferences/shared_preferences.dart';

class SettingsStore {
  static const _darkKey = 'dark_mode';

  Future<bool> loadDarkMode() async {
    final prefs = await SharedPreferences.getInstance();
    return prefs.getBool(_darkKey) ?? false;
  }

  Future<void> saveDarkMode(bool value) async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.setBool(_darkKey, value);
  }
}

A sticky note, a safe and a filing cabinet

shared_preferences is a sticky note for small reminders, secure storage is the safe for keys, and a database is the filing cabinet for records you search and update.

त्वरित जाँच: Where should you store an authentication token on the device?

  • In shared_preferences as plain text
  • In secure storage such as flutter_secure_storage
  • In a Dart global variable only
  • In the app's assets folder
Answer

In secure storage such as flutter_secure_storage — Secure storage uses the platform keychain or keystore.