Sobes.tech
Junior

What is SharedPreferences and how to use it?

sobes.tech AI

Answer from AI

SharedPreferences is a simple mechanism for storing small amounts of data in key-value pairs. It is ideal for saving user settings or small flags.

Usage:

  1. Adding dependency: In the pubspec.yaml file, add:

    dependencies:
      flutter:
        sdk: flutter
      shared_preferences: ^2.2.0 # Use the latest version
    

    and run flutter pub get.

  2. Import:

    import 'package:shared_preferences/shared_preferences.dart';
    
  3. Getting an instance:

    // Asynchronous operation
    SharedPreferences prefs = await SharedPreferences.getInstance();
    
  4. Writing data:

    // Write a string
    prefs.setString('username', 'Alice');
    // Write an integer
    prefs.setInt('age', 30);
    // Write a double
    prefs.setDouble('salary', 50000.50);
    // Write a boolean
    prefs.setBool('darkMode', true);
    // Write a list of strings
    prefs.setStringList('items', ['item1', 'item2']);
    

    All write methods return Future<bool>, indicating success.

  5. Reading data:

    // Read a string
    String? username = prefs.getString('username'); // Returns null if key not found
    // Read an integer
    int? age = prefs.getInt('age');
    // Read a double
    double? salary = prefs.getDouble('salary');
    // Read a boolean
    bool? darkMode = prefs.getBool('darkMode');
    // Read a list of strings
    List<String>? items = prefs.getStringList('items');
    
  6. Deleting data:

    // Remove by key
    prefs.remove('username'); // Returns Future<bool>
    // Clear all data
    prefs.clear(); // Returns Future<bool>
    

Limitations:

  • Not suitable for storing large amounts of data or complex structures.
  • Data is stored in plain text (though at the app level), not suitable for sensitive information.
  • Works with basic data types. For objects, serialization/deserialization (e.g., with JSON) is required.
What is SharedPreferences and how to use it? — Flutter - sobes.tech