Module 5 - Data Persistence
Module 5 - Data Persistence
1. Shared Preferences
1. Saving Data
import 'package:shared_preferences/shared_preferences.dart';
Usage:
await saveData('username', 'JohnDoe'); // Saves the key-value
pair 'username': 'JohnDoe'
2. Reading Data
// Function to read data from SharedPreferences
Future<String?> readData(String key) async {
SharedPreferences prefs = await
SharedPreferences.getInstance();
return prefs.getString(key); // Retrieve the value associated
with the key
}
Usage:
String? username = await readData('username'); // Reads the value
of 'username'
print(username); // Output: JohnDoe
Updating data is equivalent to saving data with the same key. The new value
overwrites the old one.
// Function to update (write) data in SharedPreferences
Future<void> updateData(String key, String newValue) async {
SharedPreferences prefs = await
SharedPreferences.getInstance();
await prefs.setString(key, newValue); // Overwrite the value
with the new value
}
Usage:
await updateData('username', 'JaneDoe'); // Updates 'username' to
'JaneDoe'
4. Removing Data
// Function to remove a value from SharedPreferences
Future<void> removeData(String key) async {
SharedPreferences prefs = await
SharedPreferences.getInstance();
await prefs.remove(key); // Removes the value associated with
the key
}
Usage:
dart
Copy code
await removeData('username'); // Deletes the key-value pair for
'username'
Key Points
2. Files
import 'dart:io';
This is part of the Dart standard library and provides classes for performing file
system operations, such as reading, writing, deleting, and creating files.
It's required for working with File, Directory, and other file system operations.
import 'package:path_provider/path_provider.dart';
This is a Flutter package that helps find commonly used directories on the
device's file system.
The _localPath function retrieves the directory path for storing files locally.
Future<String> get _localPath async {
final directory = await getApplicationDocumentsDirectory();
return directory.path;
}
Usage: The path can be used to locate where to create or access files.
Combines the path from _localPath with the file name (users.txt).
Returns: A File object pointing to users.txt.
Usage: This File object is used for reading and writing operations.
The writeData function writes the provided data into the specified file.
Future<File> writeData(String data) async {
final file = await _localFile;
return await file.writeAsString(data);
}
Usage:
await writeData('Hello, Flutter!');
Usage:
String? fileContent = await readData();
print(fileContent); // Output: Hello, Flutter!
Summary of Steps
3. SQLite
1. Defining the User Class
The User class represents the data model. Each User object contains:
Key Functionality:
Code:
class User {
final int id;
final String name;
final int age;
Key Steps:
Code:
Future<Database> openDatabaseConnection() async {
return openDatabase(
// Path to the database file
join(await getDatabasesPath(), 'my_database.db'),
// Database version
version: 1,
);
}
3. Inserting a User
The insertUser function adds a new User object to the users table in the
database.
Key Steps:
1. Convert Object to Map: Use the toMap method of the User object to
transform it into key-value pairs.
2. Insert Data: Use the insert method to add the data to the table.
o conflictAlgorithm: Determines the behavior when there's a
conflict (e.g., duplicate IDs).
Conflict Algorithms:
Code:
Future<void> insertUser(User user) async {
Database database = await openDatabaseConnection();
await database.insert(
'users',
user.toMap(),
conflictAlgorithm: ConflictAlgorithm.replace,
);
Workflow Explanation:
await insertUser(user);