Lecture 8 _ Data Persistence and serialization
Lecture 8 _ Data Persistence and serialization
and serialization
T.Fatima Al-azazi
Agenda
2
Storing Key-Value data
3
Store key-value data on disk
4
Using Shared_preferences
5
Save Data
● To persist data, use the setter methods provided by the
SharedPreferences class.
● Setter methods are available for various primitive types, such
as setInt, setBool, and setString.
● Setter methods do two things: First, synchronously update the
key-value pair in-memory. Then, persist the data to disk.
6
Read data
7
Remove data
await prefs.remove('counter');
8
Using Json Files
9
JSON
11
Value Types in Json
● The types of values you can use are Object, Array, String,
Boolean, and Number.
● Objects are declared by curly ({}) brackets, and inside you
use the key/value pair and arrays.
● You declare arrays by using the square ([]) brackets, and
inside you use the key/value or just the value.
12
13
14
15
Example
● The JSON file is used to save and read the journal data from the
device local storage area, resulting in data persistence over app
launches.
● You have the opening and closing curly brackets declaring an
object.
● Inside the object, the journal’s key contains an array of objects
separated by a comma.
● Each object inside the array is a journal entry with key/value
pairs declaring the id, date, mood, and note.
● The id key value is used to uniquely identify each journal entry
and isn’t displayed in the UI.
● How the value is obtained depends on the project requirement;
16
Journal App’s Json file
17
USING CLASSES TO WRITE and READ JSON
18
Retrieve the Directory Path
● The first task in local persistence is to retrieve the directory path where
the data file is located on the device.
● Local data is usually stored in the application documents directory; for iOS,
the folder is called NSDocumentDirectory, and for Android it’s AppData.
● To get access to these folders, you use the path_provider package (Flutter
plugin). You’ll be calling the getApplicationDocumentsDirectory()
method, which returns the directory giving you access to the path variable
19
Creating a File
● Once you retrieve the path, you append the data filename by
using the File class to create a File object.
● You import the dart:io library to use the File class, giving you
a reference to the file location.
20
Reading and Writing in Json
● Once you have the File object, you use the writeAsString()
method to save the file by passing the data as a String
argument.
● To read the file, you use the readAsString() method without
any arguments. Note that the file variable contains the
document
21
RETRIEVING DATA WITH THE FUTUREBUILDER
23
FutureBuilder() sample code
24
Serialization
25
Encoding and Decoding
26
jsonEncode and jsonDecode
● To serialize and deserialize JSON files, you import the dart:convert library.
● After calling the readAsString() method to read data from the stored file, you need
to parse the string and return the JSON object by using the json.decode() or
jsonDecode() function.
● Note that the jsonDecode() function is shorthand for json.decode().
● To convert values to a JSON string, you use the json.encode() or jsonEncode()
function. Note that jsonEncode() is shorthand for json.encode().
● It’s a personal preference deciding which approach to use; in the exercises, you’ll
be using json.decode() and json.encode().
27
Serialization
28
Serialization Strategies
30
Automated serialization
● JSON serialization with code generation means having an
external library generate the encoding boilerplate for you.
● After some initial setup, you run a file watcher that
generates the code from your model classes.
● For example, json_serializable and built_value are these
kinds of libraries.
● This approach scales well for a larger project. No hand-
written boilerplate is needed.
● The downside with code generation is that it requires some
initial setup.
● Also, the generated source files might produce visual clutter
in your project navigator. 31
Using Local Database
32
Local Database
33
Sqfllite package
34
Open the database
the sqflite package, combined with the join function from the path
package.
2. Open the database with the openDatabase() function from sqflite.
35
final database = openDatabase(
// Set the path to the database. Note: Using the `join` function
from the
);
36
Creating tables
create a table to store information
return db.execute(
);
},
37
Insert the Object into the database
age: maps[i]['age'],
final List<Map<String,
dynamic>> maps = await );});
db.query('dogs');
39
Update a Dog in the database
you can also remove from the database. To delete data, use the
delete() method
await db.delete(
'dogs',
whereArgs: [id],
); 41
Assignment 7
42