0% found this document useful (0 votes)
18 views

Module 5 - Data Persistence

Uploaded by

Habiba Yasser
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views

Module 5 - Data Persistence

Uploaded by

Habiba Yasser
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 7

Design Patterns

1. Shared Preferences
1. Saving Data
import 'package:shared_preferences/shared_preferences.dart';

// Function to save a value to SharedPreferences


Future<void> saveData(String key, String value) async {
SharedPreferences prefs = await
SharedPreferences.getInstance();
await prefs.setString(key, value); // Save a string value with
the given key
}

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

3. Updating (Writing) Data

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

1. Save/Update: Use setString, setBool, setInt, etc., based on data type.


2. Read: Use getString, getBool, getInt, etc.
3. Remove: Use remove for specific key-value pairs.

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.

1. Find the Correct Local Path

The _localPath function retrieves the directory path for storing files locally.
Future<String> get _localPath async {
final directory = await getApplicationDocumentsDirectory();
return directory.path;
}

 getApplicationDocumentsDirectory: Fetches the directory where


app-related files can be stored. This path is app-specific and won't
interfere with other apps.
 Returns: The directory's path as a string.

Usage: The path can be used to locate where to create or access files.

2. Create a Reference to the File Location

The _localFile function creates a reference to a specific file in the


directory.
Future<File> get _localFile async {
final path = await _localPath;
return File('$path/users.txt');
}

 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.

3. Write Data to the File

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);
}

 writeAsString: Writes the given String data into the file,


overwriting any existing content.
 Returns: A new File object after the data is written.

Usage:
await writeData('Hello, Flutter!');

 Writes the string Hello, Flutter! into users.txt.

4. Read Data from the File

The readData function reads the content of the file as a string.


Future<String?> readData() async {
try {
final file = await _localFile;
return await file.readAsString();
} catch (e) {
return null; // Returns null if an error occurs (e.g., file
not found).
}
}

 readAsString: Reads the file's contents as a string.


 Error Handling: If an exception occurs (e.g., file not found), it
returns null.

Usage:
String? fileContent = await readData();
print(fileContent); // Output: Hello, Flutter!

Summary of Steps

1. Find Local Path:


o Use _localPath to determine where to store the file.
2. Create a File Reference:
o Use _localFile to create a reference to the file at the desired
path.
3. Write Data:
o Use writeData to write string content into the file.
4. Read Data:
o Use readData to fetch the file's content.

3. SQLite
1. Defining the User Class

The User class represents the data model. Each User object contains:

 id: A unique identifier (int).


 name: The user's name (String).
 age: The user's age (int).

Key Functionality:

 Constructor: Initializes the object with its attributes.


 toMap Method: Converts the object to a map (key-value pair). This is
required because SQLite uses maps for storing data.

Code:
class User {
final int id;
final String name;
final int age;

User({required this.id, required this.name, required


this.age});

Map<String, dynamic> toMap() {


return {
'id': id,
'name': name,
'age': age,
};
}
}

2. Establishing a Database Connection


The openDatabaseConnection function sets up a connection to the SQLite
database and creates the database if it doesn't already exist.

Key Steps:

1. Database Path: Use the getDatabasesPath method from the


path_provider package and combine it with the join method from
the path package to get a platform-agnostic database path.
2. openDatabase Method: Opens or creates the database.
o onCreate Callback: Runs when the database is created. It
executes the SQL command to create the users table.
o Version: The database version for managing migrations.

Code:
Future<Database> openDatabaseConnection() async {
return openDatabase(
// Path to the database file
join(await getDatabasesPath(), 'my_database.db'),

// The `onCreate` callback


onCreate: (db, version) {
// Define the SQL command to create a table
return db.execute(
'''
CREATE TABLE users (
id INTEGER PRIMARY KEY,
name TEXT,
age INTEGER
)
'''
);
},

// 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:

 ConflictAlgorithm.abort: Aborts the operation and raises an error.


 ConflictAlgorithm.replace: Replaces the existing row with the new
one.
 ConflictAlgorithm.ignore: Ignores the new row if a conflict occurs.
 ConflictAlgorithm.update: Updates the existing row with the new
data.

Code:
Future<void> insertUser(User user) async {
Database database = await openDatabaseConnection();
await database.insert(
'users',
user.toMap(),
conflictAlgorithm: ConflictAlgorithm.replace,
);

Workflow Explanation:

1. Create a User object:

var user = User(id: 1, name: 'John Doe', age: 25);

2. Open the Database:

var db = await openDatabaseConnection();

3. Insert the User:

await insertUser(user);

You might also like