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

Lecture 12 (Persistent Storage)

The document discusses persistent storage options in Flutter, focusing on Shared Preferences and SQLite databases. Shared Preferences allows for storing user-specific configuration data in key-value pairs, while SQLite is suitable for larger structured data. The document also provides instructions on using the shared_preferences and sqflite plugins for data storage and retrieval in Flutter applications.

Uploaded by

Hasaan Bin Arif
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Lecture 12 (Persistent Storage)

The document discusses persistent storage options in Flutter, focusing on Shared Preferences and SQLite databases. Shared Preferences allows for storing user-specific configuration data in key-value pairs, while SQLite is suitable for larger structured data. The document also provides instructions on using the shared_preferences and sqflite plugins for data storage and retrieval in Flutter applications.

Uploaded by

Hasaan Bin Arif
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 16

Flutter SharedPrference

IT Industry-Academia Bridge Program


Persistent Storage
Data that is available among different sessions of an
application is called persistent data. For persistent
storage data is stored on secondary storage disks, SD
card etc.
For persistent storage, we can use external package
• Shared Preferences
• SQLite Database

IT Industry-Academia Bridge Program


Shared Preference
Android provides many ways of storing data of an application. One
of this ways is called Shared Preferences. Shared Preferences allow
you to save and retrieve data in the form of key value pair.
Key is always String, value can have either primitive type (string,
long, int ,float, and Boolean) or String type.

Shared Preference provide persistence storage, however Shared


Preferences is application specific, i.e. the data is lost on
performing one of the following options:
On uninstalling the application
On clearing the application data (through Settings)
Shared Perference
As the name suggests, the primary purpose is to store
user-specified configuration details, such as user specific
setting, keeping the user logged into the application. For
example when the user’s settings need to be saved or to
store data that can be used in different activities within
the app.
• Persist Data across user sessions, even if app is killed
and restarted, or device is rebooted
• Data that should be remembered across sessions, such
as user’s preferred settings or their game score.
• Common use is to store user preferences
Shared Preference Plugin
shared_preferences is a Flutter plugin that allows you to save data in a key-
value format so you can easily retrieve it later. Behind the scenes, it uses the
named SharedPreferences on Android and the similar UserDefaults on iOS.
Step-1 Insert dependence in pubspec.yaml
dependencies:
shared_preferences: ^2.0.15
Step-2 Add Library in file, where you call shared preference
import 'package:shared_preferences/shared_preferences.dart';
Step-3 Get instance of shared preference and call the functions to get/set
value.
final Future<SharedPreferences> _prefs = SharedPreferences.getInstance();
bool result = _prefs.setString('username', username);
Shared preference set functions: setString / setDouble / setBool / setInt
IT Industry-Academia Bridge Program
Shared Preference get functions: getString / getDouble / getBool / getInt
SharedPreference
To delete or remove data from sharedpreferences in flutter we have to
use remove() method.
deleteValue () async {
prefs = await SharedPreferences.getInstance();
prefs.remove("username");
}
To check if a key or record is present in shared preferences we have to
use containsKey() method.
checkKey () async {
prefs = await SharedPreferences.getInstance();
bool hasKey = prefs.containsKey("username");
print(hasKey);
}
IT Industry-Academia Bridge Program
Synchronous vs Asynchronous
Synchronous: In synchronous code execution, tasks are executed one after the
other, and each task must complete before the next one begins. This means
that the program waits for each operation to finish before moving on to the
next one.
Asynchronous: Asynchronous code allows tasks to be executed independently
and concurrently, without waiting for each task to complete before starting
the next one. This is particularly useful for non-blocking operations like
network requests, file I/O, or other operations that might take some time to
complete.
Dart/Flutter provides the async and await keywords to work with
asynchronous code. Functions marked with async can use await to pause
execution until a Future is complete.
Multiple SharedPreferences
In SharedPreference, normally data is stored in default SharedPreference file
-
SharedPreferences prefs = SharedPreferences.getInstance();
prefs.setString(‘key1’, ‘value1’)
To create multiple SharedPreferences files with different names, you can use
the
SharedPreferences customPrefs = await
SharedPreferences.getInstance(name: 'customPrefs');
customPrefs.setString('key1', 'value1');
You can create additional SharedPreferences files by using different names
when calling getSharedPreferences() or getInstance(name:
'yourCustomName')
SQLite Databases
Like all programming platforms, Android too supports
structured data to be stored into a database (SQLite).
Shared Preference, Internal Storage, External Storage are
useful for small data. For big structured data on local
drive, SQLite is best option. SQLite is an Open Source and
light database (available in Android as a library). It stores
database file on the device Internal Storage in private disk
space.
Programmer can control the name of database file SQLite
supports all CRUD operations (Create, Read, Update,
Delete)
IT Industry-Academia Bridge Program
SQFLite
For flutter, sqflite is a plugin for SQLite, a self contained, high-reliability,
embedded, SQL database engine. The sqflite package provides classes and
functions to interact with a SQLite database.
To use SQLite in your package, add the following dependency
dependencies:
sqflite: ^2.2.2
And import the following pakcage
import 'package:sqflite/sqflite.dart';
To Access/Open Database, use getDatabasePath function defined in sqflite
package.
String databaseName = “student.db”
String databasePath = await getDatabasesPath(); //get the default database location define in sqflite package
String path = join(await databasePath, databaseName); // join databasepath/databasename define path package
final database = openDatabase(path);
Future<Database> openDatabase(
String path,
{int? version,
OnDatabaseConfigureFn? onConfigure,

OpenDatabase Function OnDatabaseCreateFn? onCreate,


OnDatabaseVersionChangeFn? onUpgrade,
OnDatabaseVersionChangeFn? onDowngrade,
OnDatabaseOpenFn? onOpen,
String? password,
bool readOnly = false,
bool singleInstance = true}
)

The openDatabase function is a method provided by the sqflite package


in flutter, and it is used to open a connection to a SQLite database.
The openDatabase function takes a path to the data base file and an
optional set of parameters.
path: This is the path to the database file. If the file does not exist, it will
be created.
version: This is an integer that represents the version of the database
schema. If this value is greater than the current version of the database,
the onCreate callback will be called to create the new schema.
OpenDatabase Function
• onCreate: This is a callback function that is called when the database is
first created. It is responsible for creating the initial schema for the
database.
• onUpgrade: This is a callback function that is called when the database
version is increased. It is responsible for migrating the schema from the
old version to the new version.
• onDowngrade: This is a callback function that is called when the
database version is decreased. It is responsible for downgrading the
schema from the old version to the new version.
• readOnly: This is a boolean value that indicates whether the database
should be opened in read-only mode.
IT Industry-Academia Bridge Program
Open Connection to SQLite
Database
To open connection to SQLite Database
String databaseName = “user.db";
String databasePath = await getDatabasesPath(); //get the default database location define in sqflite packag
String path = join(await databasePath, databaseName); // join databasepath/databasename define in path package

final database = openDatabase(path,


onCreate: (db, version){
print('$db $version');
return db.execute('CREATE TABLE cats(id INTEGER PRIMARY KEY, name TEXT, age INTEGER )');
},
version: 1
) as Database;
Insert Data in SQLite Database
Future<int> insert( String table, Map<String, Object?> values) class User {
final int id;
final String name;
final int age;

User({this.id, this.name, this.age});


User user = User(123, ‘Noman’, 25)
Future void _initDB async ( Map<String, dynamic> toMap() {
String table = 'users_table'; return {'id': id, 'name': name, 'age': age};
String colId = 'id'; }
String colName = 'name'; }
String colAge = 'age';
String creatTable = 'CREATE TABLE $table($colId INTEGER PRIMARY KEY AUTOINCREMENT, $colName TEXT, $colAge INTEGER’
String dbPath = await getDatabasesPath();
String path = join(dbPath, 'users.db');
final database = openDatabase(path,
onCreate: (db, version){
return db.execute(createTable);
}, version: 1
) as Database;
database.insert(table, user.toMap)
)
Get Data in SQLite Database
Future<List<Map<String, Object?>>> query( Future void displaydb async (
String table, { final List<Map<String, dynamic>> maps = await db.query(table);
List<User> _users = List.generate(maps.length, (i) {
bool? distinct, return User(
List<String>? columns, id: maps[i]['id'],
name: maps[i]['name'],
String? where,
age: maps[i]['age'],
List<Object?>? whereArgs, );
String? groupBy, });
) Expanded (
String? having,
child: ListView.builder(
String? orderBy,
itemCount: _users.length,
int? limit, itemBuilder: (context, index) {
int? offset, } User user = _users[index];
return ListTile(
)
title: Text(user.name),
subtitle: Text(user.age.toString()),
); },
) )
Reference
https://blog.devgenius.io/using-sqlite-in-flutter-4b16e5ef36dc
https://pub.dev/packages/sqflite_common_ffi/example
https://morioh.com/p/46319d1993b4

IT Industry-Academia Bridge Program

You might also like