Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 24

Mobile Application Development using Flutter

(MADF) (2105CS303)

Unit : 3
Storages & Database
Connectivity

Prof. Mehul Bhundiya


Computer Science & Engineering Department
Darshan Institute of Engineering & Technology, Rajkot
mehul.bhundiya@darshan.ac.in
+91 - 9428231065
Asynchronous programming
 In synchronous programming, each person would have to wait for the person before them to
finish their task before starting their own.
 Asynchronous programming allows a program to work on multiple tasks simultaneously
instead of completing one task before moving on to the next one.
 This can make the program get more things
done in a shorter amount of time.
 Asynchronous operations let your program
complete work while waiting for another
operation to finish.
 Here are some common asynchronous
operations:
 Fetching data over a network. https://www.freecodecamp.org/news/asynchronous-programming-in-javascript/

 Writing to a database.
 Reading data from a file.

Prof. Mehul Bhundiya #2105CS303 (MDAF)  Unit 3 – Storages & Database Connectivity 2
Future
 A Future is an object that represents the result of an asynchronous operation.
 This is the indicator that we use to identify asynchronous operations in Dart.
 Future is a placeholder for a value that will exist.
 Imagine you’re visiting a hamburger
restaurant.
 In the restaurant, you order your
burger at the counter and get a receipt.
 Futures are a lot like that receipt that
guarantees you’ll get a burger as soon
as one is ready.
 So, you go wait until the server calls
your number, and then delivers on the
guarantee of a burger.
 The burger is the value, not the future.
Prof. Mehul Bhundiya #2105CS303 (MDAF)  Unit 3 – Storages & Database Connectivity 3
async
 Any functions you want to run asynchronously need to have the async modifier added to it.
 This modifier comes right after the function name.
Syntax
1 Future<void> hello() async {
2 print('Darshan University');
3 }

 When an async function is called, a Future is immediately returned and the body of the
function is executed later.
 As the body of the async function is executed, the Future returned by the function call will be
completed along with its result.
 In the above example, calling hello() results in the Future.
 Typically, the function you want to run asynchronously would have some expensive operation
in it like file I/O, an API call to a RESTful service, Executing database query.

Prof. Mehul Bhundiya #2105CS303 (MDAF)  Unit 3 – Storages & Database Connectivity 4
await
 Await expressions makes you write the asynchronous code as synchronous.
Syntax Example: synchronous functions
1 Future<void> main() async { 1 String createOrderMessage() {
2 await hello(); 2 var order = fetchUserOrder();
3 print('Darshan University'); 3 return 'Your order is: $order';
4 } 4 }
5
 You can use the await keyword to 6 Future<String> fetchUserOrder() {
7 Future.delayed(
get the completed result of an 8 Duration(seconds: 2),
asynchronous expression. 9 () => 'Large Latte', );
10 }
 The await keyword works only in 11
async functions. 12 void main() {
13 print('Fetching user order...');
 In example we had written code as 14 print(createOrderMessage());
15 }
synchronous code without
async/await. Output
 Output diplays the instance of future Fetching user order...
Your order is: Instance of '_Future<String>'
as returned value.
Prof. Mehul Bhundiya #2105CS303 (MDAF)  Unit 3 – Storages & Database Connectivity 5
await asynchronous example
 The return type for createOrderMessage() Example: asynchronous functions
changes from String to Future<String>. 1 Future<String> createOrderMessage() async {
2 var order = await fetchUserOrder();
 The async keyword appears before the 3 return 'Your order is: $order';
4 }
function bodies for createOrderMessage() 5
and main(). 6 Future<String> fetchUserOrder() {
7 Future.delayed(
 The await keyword appears before calling 8 Duration(seconds: 2),
the asynchronous functions 9 () => 'Large Latte', );
fetchUserOrder() and 10 }
11
createOrderMessage(). 12 Future<void> main() async {
13 print('Fetching user order...');
14 print(await createOrderMessage());
15 }

Output
Fetching user order...
Your order is: Large Latte

Prof. Mehul Bhundiya #2105CS303 (MDAF)  Unit 3 – Storages & Database Connectivity 6
Future Builder
 FutureBuilder is a Widget that will help you to execute some asynchronous function and
based on that function’s result UI will update.
 FutureBuilder is Stateful by nature.
 When we use the FutureBuilder widget we need to check for future state.
 There is various State as follows
 ConnectionState.none: It means that the future is null and initialData is used as defaultValue.
 ConnectionState.active: It means the future is not null but it is not resolved yet.
 ConnectionState.waiting: It means the future is being resolved, and we will get the result soon enough.
 ConnectionState.done: It means that the future has been resolved.
Future
1 Future<String> getData() {
2 return Future.delayed(Duration(seconds: 2), () {
3 return "I am data";
4 }
5 );
6 }

Prof. Mehul Bhundiya #2105CS303 (MDAF)  Unit 3 – Storages & Database Connectivity 7
Future Builder Example
Future Builder
1 @override
2 Widget build(BuildContext context) {
3 return Scaffold(
4 body: FutureBuilder(
5 builder: (ctx, snapshot) {
6 if (snapshot.connectionState == ConnectionState.done) {
7 if (snapshot.hasError) {
8 return Text(
9 '${snapshot.error} occurred');
10 } else if (snapshot.hasData) {
11 final data = snapshot.data as String;
12 return Text('$data');
13 }
14 }
15 return Center(
16 child: CircularProgressIndicator());
17 },
18 future: getData(),
19 ));
20 }
21 }

Prof. Mehul Bhundiya #2105CS303 (MDAF)  Unit 3 – Storages & Database Connectivity 8
Storages available in flutter
 All the data are stored in variables but it is not permanently.
 When ever we start application again it initializes with default value.
 For Example: int a = 10;
 To overcome this situation we need to store data in place where it cannot deleted
automatically or initialize with default value.
 Not all data is created equally and not all data should be stored the same way.
 Similar to learning about HashMaps, Linked Lists, Heaps, etc., it’s important to know the
different ways to store data in your Flutter App to create the best user experience possible.
 There are two types of storages available
 1) Local storage
 2) Cloud Storage

Prof. Mehul Bhundiya #2105CS303 (MDAF)  Unit 3 – Storages & Database Connectivity 9
Local Storage
 Local storage stores data locally to the device hence it don’t need network connection to
access it.
 Local storage do not share data between devices.
 Different types of local storage available as below
 Shared Preferences
 SQLite Database
 File Storage

Prof. Mehul Bhundiya #2105CS303 (MDAF)  Unit 3 – Storages & Database Connectivity 10
Shared Preference
 Shared Preferences is the used to store a small amount of data in flutter projects.
 It Stored primitive data as key/value pairs to a file on the device storage.
 It make up an XML file inside the app on the device storage.
 Shared Preferences in flutter uses NSUserDefaultson iOS and SharedPreferences on Android,
providing a persistent store for simple data.
 Shared Preferences is not a solution for you to keep complex relational data.
 Flutter SDK does not have support SharedPreferences.
 the shared_preferences plugin can be used to persist key-value data on disk.
Implementation
1 dependencies:
2 flutter:
3 sdk: flutter
4 shared_preferences: "<newest version>"

 When we are store the data inside the storage through SharedPreferences we
have to pass key and value both.
Prof. Mehul Bhundiya #2105CS303 (MDAF)  Unit 3 – Storages & Database Connectivity 11
Store Data Inside Shared Preference
Insert Name
1 SharedPreferences prefs = await
2 SharedPreferences.getInstance();
3
4 prefs.setString('Name', "DU"); Key: Type
Name
Value: University
DU
Darshan

 It will store DU as value inside file with key


Name.
Insert Name
1 SharedPreferences prefs = await
2 SharedPreferences.getInstance(); Shared Preference
3
4 prefs.setString('Name', "Darshan");

 It will replace Darshan with DU as value inside file with key


Name.Type
Insert
1 SharedPreferences prefs = await  It will store University as value with
2 SharedPreferences.getInstance();
3 key Type.
4 prefs.setString('Type', "University");

Prof. Mehul Bhundiya #2105CS303 (MDAF)  Unit 3 – Storages & Database Connectivity 12
Retrieve data from Shared Preference
 When we are reading the data from the
storage we only required to pass the key only. NULL Key: Type
name
Name

Retrieve name Key:University


Type
Value: University
1 SharedPreferences prefs = await Key: Name
2 SharedPreferences.getInstance(); Value:Darshan
Darshan

3
4 String? name = prefs.getString('name'); Shared Preference
 When we pass name as key it will return NULL as value because name
key not found inside file.
Retrieve Name
1 SharedPreferences prefs = await  When we pass Name as key it will return
2 SharedPreferences.getInstance();
3
Darshan as value because it is found in file.
4 String? name = prefs.getString('Name');

Retrieve Type
1 SharedPreferences prefs = await
 When we pass Type as key it will return
2 SharedPreferences.getInstance(); University as value because it is found in
3 file.
4 String? name = prefs.getString('NType');
Prof. Mehul Bhundiya #2105CS303 (MDAF)  Unit 3 – Storages & Database Connectivity 13
Shared Preference
 We can store String, integer, float, Boolean & List data inside Shared Preference.
Store Data Read Data
1 SharedPreferences prefs = await 1 SharedPreferences prefs = await
2 SharedPreferences.getInstance(); 2 SharedPreferences.getInstance();
3 3
4 // Save an integer value to 'num' key. 4 // Get an integer value from 'num' key.
5 await prefs.setInt('num', 10); 5 int? num = await prefs.getInt('num');
6 6
7 // Save an boolean value to 'flag' key. 7 // Get an boolean value from 'flag' key.
8 await prefs.setBool('flag', true); 8 bool? flag= await prefs.getBool('flag');
9 9
10 // Save an double value to 'decnum' key. 10 // Get an double value from 'decnum' key.
11 await prefs.setDouble('decnum', 1.5); 11 double? decNum = await prefs.getDouble('decnum');
12 12
13 // Save an String value to 'name' key. 13 // Get an String value from 'name' key.
14 await prefs.setString('name', 'Start'); 14 String? name = await prefs.getString('name');
15 15
16 // Save an list of strings to 'items' key. 16 // Get an list of strings from 'items' key.
17 await prefs.setStringList('items', 17 List<String> list = await
18 <String>['Earth', 'Moon', 'Sun']); 18 prefs.getStringList('items');

Prof. Mehul Bhundiya #2105CS303 (MDAF)  Unit 3 – Storages & Database Connectivity 14
Remove data from Shared Preference
 To remove the data from the storage we provide the key in the remove(String key) method.
Delete Data
1 SharedPreferences prefs = await
2 SharedPreferences.getInstance();
3
4 var success = await prefs.remove('Name')

Prof. Mehul Bhundiya #2105CS303 (MDAF)  Unit 3 – Storages & Database Connectivity 15
Sqlite Database
 SQLite is a C-language library that implements a small, fast, self-contained, high-reliability,
full-featured, SQL database engine.
 SQLite is not directly comparable to client/server SQL database engines such as MySQL,
Oracle, PostgreSQL, or SQL Server.
 Client/server SQL database engines strive to implement a shared repository of enterprise
data.
 An
 SQLite
app provide local
that needs to data storage
persist for individual
and query applications
large amounts and devices.
of data Pubspec.yaml
on the local device, consider using a database instead of a 1 dependencies:
2 cupertino_icons: ^1.0.2
local file or key-value store. 3 flutter:
 Databases provide faster inserts, updates and queries 4 sdk: flutter
5 path: 'Lates Version'
compared to other local storages. 6 sqflite: 'Lates Version'
 Flutter apps can make use of the SQLite databases via the
sqflite plugin.

Prof. Mehul Bhundiya #2105CS303 (MDAF)  Unit 3 – Storages & Database Connectivity 16
Sqlite Database
 An app that needs to persist and query large amounts of data on the local device, consider
using a database instead of a local file or key-value store.
 Databases provide faster inserts, updates and queries compared to other local storages.
 Flutter apps can make use of the SQLite databases via the sqflite plugin.
 Now you can create database in flutter using two different ways.
 1) Create database using query inside onCreate() function.
 2) Attach external db file by copy-paste from asset folder to root of phone.

Prof. Mehul Bhundiya #2105CS303 (MDAF)  Unit 3 – Storages & Database Connectivity 17
Create database
 To create database first we have to initialize database object to perform operation on it.
Create Database
1 Future<Database> initializedDB() async {
2 String path = await getDatabasesPath();
3 return openDatabase(
4 join(path, 'UserInfo.db'),
5 version: 1,
6 onCreate: (Database db, int version) async {
7 await db.execute(
8 "CREATE TABLE User(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)",
9 );
10 },
11 );
12 }

 When openDatabase() executed it will create an empty UserInfo database inside root folder
of the device where installed application data is stored and it is not directly accessed by user.
 Version indicates current version of database & onCreate() will create User Table inside
UserInfo database with id, name as columns.
Prof. Mehul Bhundiya #2105CS303 (MDAF)  Unit 3 – Storages & Database Connectivity 18
Insert Data
 After creating database successfully now we can insert data inside User table when ever
needed.
 To insert record in table first we need the reference of the database. Database db = await initializedDB();
 Then we have to map data with column using Map<String,dynamic>.
1 Map<String, dynamic> map = {};
2 map['Name'] = userName;

 Finally we can store data in table using db.insert() method. 1 await db.insert(User', map);

Example
1 Future<int> insertIntoUserTable({String? name}) async { User
2 Database db = await initDatabase(); id name
3 Map<String, dynamic> map = {};
1 Darshan
4 map['Name'] = name;
5 return await db.insert('User', map); 2 University
6 }
Function Call
1 await insertIntoUserTable(name:'Darshan');
insertIntoUserTable(name:'University');

Prof. Mehul Bhundiya #2105CS303 (MDAF)  Unit 3 – Storages & Database Connectivity 19
Update Data
 To update information of inserted data at a later time can be done by using the update()
method from the sqflite library.
 This involves two steps
 Convert the information into a Map.
 Use a where clause to ensure you update the correct information.
Syntax
1 await db.update('TABLE NAME',map, where: 'id = ?', whereArgs: [id],);

 Always use whereArgs to pass arguments to a where statement.


Example User
1 Future<int> updateIntoUserTable({String? name,int? id}) async { id name
2 Database db = await initDatabase(); 1 Darshan
DU
3 Map<String, dynamic> map = {};
4 map['Name'] = name; 2 University
5 return await db.update('User', map,where: 'id=?',
6 whereArgs:[id]);
7 }
Function Call
1 await updateIntoUserTable(name:'DU',id:1);
Prof. Mehul Bhundiya #2105CS303 (MDAF)  Unit 3 – Storages & Database Connectivity 20
Read Data
 To get data from database, query the database for a specific record or a list of all records.
 This involves following steps
 Run a query against the table.
 This returns a List<Map>.
 Convert the List<Map> into a List<Model>.
Syntax
1 await db.rawQuery('SELECT * FROM TABLE');

 Always use whereArgs to pass arguments to a where statement.


Syntax
1 await db.rawQuery('SELECT * FROM TABLE WHERE ID = ?', whereArgs: [ID]);

Prof. Mehul Bhundiya #2105CS303 (MDAF)  Unit 3 – Storages & Database Connectivity 21
Read Data
Example User
1 Future<List<UserModel>> getDataFromTblUser() async { UserID Name City
2 Database db = await getDatabaseReference();
3 List<Map<String, Object?>> userList =
1 DU Rajkot
4 await db.rawQuery('SELECT * FROM Tbl_User'); 2 University Surat
5 return List.generate(
6 userList.length,
3 BCA Ahmedaba
7 (index) => UserModel.name( d
4 MCA Vadodara
8 userList[index]['UserID'] as int,
9 userList[index]['Name'].toString(),
10 userList[index]['City'].toString(),
11 ),
12 );
13 }

Prof. Mehul Bhundiya #2105CS303 (MDAF)  Unit 3 – Storages & Database Connectivity 22
Delete Data
 To delete data from the database use the delete() method from the sqflite library.
 create a function that takes an id and deletes the data with a matching id from the database.
 To make this work, you must provide a where clause to limit the records being deleted.
Syntax
1 await db.delete('Table', where: 'id = ?', whereArgs: [id]);

Example User
1 Future<void> deleteUser({required int id}) async { UserID Name City
2 Database db = await getDatabaseReference();
3 await db.delete('Tbl_User',
1 DU Rajkot
4 where: 'id = ?',whereArgs: [id],); 2 University Surat
5 }
3 BCA Ahmedaba
d
Function Call 4 MCA Vadodara
1 await deleteUser(id:4);

Prof. Mehul Bhundiya #2105CS303 (MDAF)  Unit 3 – Storages & Database Connectivity 23
Thank You

You might also like