free geoip
50

Save Data Using SharedPreferences in Dart

Saving user preferences or small bits of data locally is a common requirement in many mobile apps. In Flutter, the…

Saving user preferences or small bits of data locally is a common requirement in many mobile apps. In Flutter, the SharedPreferences plugin is the go-to solution for storing key-value pairs efficiently and securely. This article will guide you on how to save data using SharedPreferences in Dart, complete with a full example broken down into multiple classes for better structure.

SharedPreferences in Dart

🔹 Why Use SharedPreferences?

SharedPreferences is ideal for saving small, persistent key-value data. It’s commonly used for storing:

  • Login tokens
  • Theme preferences
  • User settings
  • App walkthrough status

🔹 Installation

First, include the dependency in your pubspec.yaml file:

dependencies:
  shared_preferences: ^2.0.15

🔹 Code Implementation (Well-Structured)

Let’s break this implementation into three classes: a helper class, a UI example, and a model (optional but good practice).

1. shared_prefs_helper.dart
import 'package:shared_preferences/shared_preferences.dart';

class SharedPrefsHelper {
  static Future<void> saveString(String key, String value) async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.setString(key, value);
  }

  static Future<String?> getString(String key) async {
    final prefs = await SharedPreferences.getInstance();
    return prefs.getString(key);
  }

  static Future<void> remove(String key) async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.remove(key);
  }
}

2. home_page.dart

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

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

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

class _HomePageState extends State<HomePage> {
  final TextEditingController _controller = TextEditingController();
  String _savedValue = '';

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

  Future<void> _loadValue() async {
    final value = await SharedPrefsHelper.getString('username');
    setState(() {
      _savedValue = value ?? '';
    });
  }

  Future<void> _saveValue() async {
    await SharedPrefsHelper.saveString('username', _controller.text);
    _loadValue();
  }

  Future<void> _removeValue() async {
    await SharedPrefsHelper.remove('username');
    _loadValue();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('SharedPreferences Demo')),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          children: [
            TextField(controller: _controller),
            const SizedBox(height: 10),
            ElevatedButton(onPressed: _saveValue, child: const Text('Save')),
            ElevatedButton(onPressed: _removeValue, child: const Text('Remove')),
            const SizedBox(height: 20),
            Text('Saved Value: $_savedValue'),
          ],
        ),
      ),
    );
  }
}

🔹 Best Practices

  • Avoid storing sensitive information like passwords directly in SharedPreferences.
  • Use encryption for confidential data.
  • Consider alternatives like Hive or secure storage for larger or more secure needs.

🔹 Conclusion

SharedPreferences is an efficient way to manage simple app data locally in Dart. It’s easy to implement, fast, and supported by Flutter across all major platforms.

rysasahrial

Leave a Reply

Your email address will not be published. Required fields are marked *