πŸŽ‡Persistence

Data persistence is crucial for maintaining data across app launches. Flutter offers several options for data persistence, and one of the most common is using the shared_preferences package for storing simple data, and the sqflite package for more complex or structured data.

1. Shared Preferences πŸ”„

For simple data storage, shared_preferences is a great choice. It allows you to store simple data in key-value pairs.

Setup:

Add the shared_preferences package to your pubspec.yaml file:

dependencies:
  flutter:
    sdk: flutter
  shared_preferences: ^2.2.2

Usage:

import 'package:shared_preferences/shared_preferences.dart';

Future<void> saveName() async {
  SharedPreferences prefs = await SharedPreferences.getInstance();
  await prefs.setString('name', 'John Doe');
}

Future<String?> getName() async {
  SharedPreferences prefs = await SharedPreferences.getInstance();
  return prefs.getString('name');
}

2. SQLite with sqflite πŸ—„οΈ

For more structured data, you might want to use a local database such as SQLite.

Setup:

Add the sqflite and path_provider packages to your pubspec.yaml file:

Usage:


Complete Example Code πŸ“œ

Here's a simple example demonstrating how to use sqflite or shared_preference for data persistence in Flutter:


Assignments πŸ“

Last updated

Was this helpful?