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

Lesson5 - Introduction to Shared Preferences and Databases.pptx

The document provides an introduction to Shared Preferences and databases in Flutter, detailing how to install and use Shared Preferences for storing simple key-value data. It also compares SQL and NoSQL databases, explaining their structures, schemas, scalability, and use cases. Additionally, it outlines how to use SQLite for local data storage in Flutter, including creating a database helper class and performing CRUD operations.

Uploaded by

Loki Legends
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

Lesson5 - Introduction to Shared Preferences and Databases.pptx

The document provides an introduction to Shared Preferences and databases in Flutter, detailing how to install and use Shared Preferences for storing simple key-value data. It also compares SQL and NoSQL databases, explaining their structures, schemas, scalability, and use cases. Additionally, it outlines how to use SQLite for local data storage in Flutter, including creating a database helper class and performing CRUD operations.

Uploaded by

Loki Legends
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 31

INTRODUCTION TO SHARED

PREFERENCES AND DATABASES

FLUTTER
• A simple key-value storage system used to store
small amounts of data persistently in a Flutter
app. It's useful for storing user settings, SHARED PREFERENCES
authentication tokens, or simple app
preferences.
HOW TO INSTALL SHARED PREFERENCES IN FLUTTER?
Method 1: Simply from the command line of your flutter project.

Run this command: flutter pub add shared_preferences

This will add a line like this to your package’s


pubspec.yaml (and If the automatic implicit
execution doesn’t happen then run an implicit
dart/flutter pub get ): flutter pub get

NOTE:
dart pub get - For Dart projects
flutter pub get - For Flutter projects

To use the shared preferences to your dart code Import this:


import 'package:shared_preferences/shared_preferences.dart';
HOW TO INSTALL SHARED PREFERENCES IN FLUTTER?
Method 2: By adding explicitly to your package’s pubspec.yaml:

Step 1: Visit the flutter site https://pub.dev/packages/shared_preferences/install to check the latest version of shared preferences:

Step 2: Copy the package/the version (for example: shared_preferences: ^2.5.1).

Step 3: Go to the pubspec.yaml in your flutter project to input the plugin. Under dependencies add a line like this to your package's
pubspec.yaml.

Step 4: If the automatic implicit execution doesn’t happen then run an implicit flutter/dart pub get:
dart pub get - For Dart projects
flutter pub get - For Flutter projects

Step 5: To use the shared preferences to your dart code Import this:
import 'package:shared_preferences/shared_preferences.dart';
HERE ARE SMALL EXAMPLES THAT SHOW YOU HOW TO USE THE API (SHARED
PREFERENCES).
// Obtain shared preferences.
final SharedPreferences prefs = await SharedPreferences.getInstance();

// Save an integer value to 'counter' key.


await prefs.setInt('counter', 10);

// Save an boolean value to 'repeat' key.


await prefs.setBool('repeat', true);
Note: These are what we use to write data. The
key name is where the value is stored.
// Save an double value to 'decimal' key.
await prefs.setDouble('decimal', 1.5);

// Save an String value to 'action' key.


await prefs.setString('action', 'Start');

// Save an list of strings to 'items' key.


await prefs.setStringList('items', <String>['Earth', 'Moon', 'Sun']);
HERE ARE SMALL EXAMPLES THAT SHOW YOU HOW TO USE THE API (SHARED
PREFERENCES).
// Obtain shared preferences.
final SharedPreferences prefs = await SharedPreferences.getInstance();

// Try reading data from the 'counter' key. If it doesn't exist, returns null.
final int? counter = prefs.getInt('counter'); Note: This is the way to read
the data we previously wrote
// Try reading data from the 'repeat' key. If it doesn't exist, returns null. from the previous page. The
final bool? repeat = prefs.getBool('repeat'); key name used when writing
the data is the same key
// Try reading data from the 'decimal' key. If it doesn't exist, returns null. name you need to call to
final double? decimal = prefs.getDouble('decimal'); read or retrieve its value.

// Try reading data from the 'action' key. If it doesn't exist, returns null.
final String? action = prefs.getString('action');

// Try reading data from the 'items' key. If it doesn't exist, returns null.
final List<String>? items = prefs.getStringList('items');
OTHER COMMANDS USED IN SHARED PREFERENCES:
// Remove data for the 'counter' key.
await prefs.remove('counter');

// Clear all the data from the shared prefernces


await prefs.clear();

// Obtain shared preferences.


Note: We always include this when writing, reading, or removing data, or whenever we need to use the methods/functions of
SharedPreferences.
final SharedPreferences prefs = await SharedPreferences.getInstance();

prefs – is the instance of SharedPreferences or the object we used to call the methods or functions of SharedPreferences.

SharedPreferences prefs – this is how we declare the variable prefs na ang type is SharedPreferences.

await - Ensures that the getInstance() function completes before proceeding (since it is an asynchronous operation).

getInstance() - initializes SharedPreferences (singleton pattern).


BASIC EXAMPLE USING SHARED PREFERENCES (SEE NOTES FOR THE COMPLETE
CODES):

Import the shared preferences


package so that you can use the
syntax code that allow our app to
store and retrieve simple data
persistently.
This is an example of how we can write data using
SharedPreferences. Since the user will input the data for the
‘username’ key, we use a TextEditingController named
controller, which manages the user’s typed username in the
text field.

We use prefs.setString() because we are storing text in the


‘username’ key. The prefs variable is a SharedPreferences
type, and it serves as our instance to write data using the
.setString(‘key’, value) method. Then, we store the user's
typed username in a String variable named ‘savedUsername’
using the setState() function.

setState() is called to update the widget's state and rebuild


the UI with the new data value.
We called the loadUsername() function here because we need to set it
up first (loading stored data from ‘savedUsername’) before displaying
the widget or data on the screen. This also ensures that there is data
or value in the username key when it renders on the screen.

initState() is a lifecycle method that is called when a StatefulWidget


is inserted into the widget tree.

This is an example of how we can read data using SharedPreferences,


or how we retrieve the value stored in our key.

We used prefs.getString() to get the value, and since the datatype for
the ‘username’ key is a string. The prefs variable is a
SharedPreferences type. This is our instance to read data using the
.getString(‘key’) method.

And if you notice, we also added ?? (null-aware operator). This means


that if the left side of ?? is not null, it will return its value (the data
the user typed). But if it is null, the right-side value of ?? will be used
as the value for the expression (our string variable savedUsername).
This is the way we remove a value from our key.

We use prefs.remove() to remove the value stored in our key.


The prefs variable is a SharedPreferences type, and it serves
as our instance to remove data using the .remove(‘key’)
method.

Once we have an instance (prefs), we can call its methods


like: .remove(), .setString(), .getString() and etc.

Then the rest of this codes are how we build our UI for this
simple example of using shared preferences.

We called the string we used to display, creating buttons to


call or execute the functions we created.
• SQL databases are primarily called Relational
Databases (RDBMS); whereas NoSQL databases DIFFERENCE BETWEEN
are primarily called non-relational or distributed
SQL AND NOSQL
databases.
DIFFERENCE BETWEEN SQL AND NOSQL

Aspect SQL (Relational) NoSQL (Non-relational)

Document-based, key-value, column-family, or


Data Structure Tables with rows and columns
graph-based

Schema Fixed schema (predefined structure) Flexible schema (dynamic and adaptable)

Scalability Vertically scalable (upgrading hardware) Horizontally scalable (adding more servers)

Data Integrity ACID-compliant (strong consistency) BASE-compliant (more available, less consistent)

Varies (e.g., MongoDB uses its own query


Query Language SQL (Structured Query Language)
language)

Better for large-scale data and fast read/write


Performance Efficient for complex queries and transactions
operations

Ideal for big data, real-time web apps, and data


Use Case Best for transactional systems (banking, ERP, etc.)
lakes

Examples MySQL, PostgreSQL, Oracle, MS SQL Server MongoDB, Cassandra, CouchDB, Neo4j
WHAT IS SQL?
SQL databases, also known as Relational Database Management Systems (RDBMS), use structured tables to store
data. They rely on a predefined schema that determines the organization of data within tables, making them suitable for
applications that require a fixed, consistent structure.
•Structured Data: Data is organized in tables with rows and columns, making it easy to relate different types of
information.

•ACID Compliance: SQL databases follow the ACID properties (Atomicity, Consistency, Isolation, Durability) to ensure
reliable transactions and data integrity.

•Examples: Popular SQL databases include MySQL, PostgreSQL, Oracle, and MS SQL Server.
WHEN TO CHOOSE SQL?
SQL databases are well-suited for use cases where:
•Data consistency and transactional integrity are critical (e.g., banking systems, customer relationship management).

•The application needs a well-defined schema and structured data.

•Complex queries and relational data are involved.

•Applications requiring multi-row transactions (such as inventory management) benefit from SQL’s robust features.
WHAT IS NOSQL?
NoSQL databases, on the other hand, are designed to handle unstructured or semi-structured data. Unlike SQL
databases, NoSQL offers dynamic schemas that allow for more flexible data storage, making them ideal for handling
massive volumes of data from various sources.
•Flexible Schema: NoSQL databases allow the storage of data without a predefined structure, making them more
adaptable to changing data requirements.

•CAP Theorem: NoSQL databases are designed based on the CAP theorem (Consistency, Availability, Partition Tolerance),
which prioritizes availability and partition tolerance over strict consistency.

•Examples: Well-known NoSQL databases include MongoDB, Cassandra, CouchDB, and HBase.
WHEN TO CHOOSE NOSQL?
NoSQL databases are a better choice when:
•You need to handle large, unstructured data sets, like social media data or logs.

•The application requires horizontal scalability to accommodate high traffic and big data.

•There is a need for real-time data processing and flexible data models (e.g., a content management system).

•You are dealing with applications requiring frequent changes in data structures.
SQL VS NOSQL: WHICH IS FASTER?
•SQL Databases: Generally, SQL databases perform well for complex queries, structured data, and systems
requiring data consistency and integrity. However, as the volume of data grows, they may struggle
with scalability and may require significant infrastructure upgrades.

•NoSQL Databases: NoSQL databases excel in scenarios that demand high performance and scalability. Because of
their horizontal scalability (accommodating more servers), they handle large amounts of data and high-velocity
workloads better. For instance, MongoDB or Cassandra is a common choice when dealing with big data or applications with
high traffic.
• SQLite is a great choice for local data storage in USING SQLITE FOR
Flutter when working with structured data. The
sqflite package provides a way to interact with
LOCAL DATA STORAGE
SQLite databases efficiently. IN FLUTTER.
USING SQLITE FOR LOCAL DATA STORAGE IN FLUTTER (WITH SQFLITE)

First Step: ADD dependencies


❖ Add sqflite and path to pubspec.yaml:

Note: Use the latest version if available.


sqflite - manages the database (CRUD operations, queries).
Path - ensures the database is stored correctly across different devices.
❖ Then run the commad flutter pub get
Second Step: Create a Database Helper Class
❖ We will create a singleton class DatabaseHelper to manage database creation, queries, and CRUD operations. Create a
database_helper.dart file at lib folder for this.

How to create a dart file?


❑ Hover your cursor At lib folder then right click on your mouse, after that a selection will appear and choose new file.
❑ Type ‘database_helper.dart‘ as the file name and tap enter.

❖ At the file we will insert these line of codes (see notes for complete codes):

Importing the packages:


❖ sqflite: Allows SQLite database operations (creating tables, inserting, updating, deleting, querying).
❖ path: Helps construct the correct database file path across different platforms.
Singleton Pattern for DatabaseHelper
❖ Ensures only one instance of DatabaseHelper exists (singleton pattern).
❖ _instance: Stores the single instance of DatabaseHelper.
❖ _database: Holds the database connection.

Make a getter for database


❖ If _database is already initialized, return it.
❖ Otherwise, initialize the database using _initDatabase().
Initializing the Database (_initDatabase)
❖ getDatabasesPath(): Gets the default
location for storing databases.
❖ join(): Ensures a correct file path across
platforms.

❖ openDatabase(path, version, onCreate):


Opens or creates the database.
❖ version: 1: Sets the database version
(used for migrations).
❖ onCreate: Executes SQL to create the
users table.

Table Schema (users table): this will be users table content


Column Type Constraints
id Integer Primary Key, Auto Increment
name Text Required
age Integer Required
Inserting Data
❖ Gets the database instance.
❖ Uses db.insert('users', {...}) to add a new user.

Retrieving Data
❖ Gets the database instance.
❖ Runs db.query('users') to fetch all users as a list of maps..
Updating Data
❖ Updates a user's name and age where id matches.
❖ whereArgs: [id]: Prevents SQL injection.

Deleting Data
❖ Deletes the user where id matches.
❖ whereArgs: [id]: Prevents SQL injection.
Third Step: Using SQLite in Flutter UI
❖ Now, let's create a simple UI to interact with the database.
❖ At the file we will insert these line of codes (see notes for complete codes):

Importing packages
❖ import 'package:flutter/material.dart’; - We need to import
this so that we can use material design components for
the User interface.
❖ import 'database_helper.dart’; - We need to import our
helper class for us to be able to interact with the SQLite
database we created from database_helper.dart file.

Entry point ( main() function)


❖ We need to call runApp to start our application which
inside is our MyApp widget to run.

MyApp Widget (Root Widget)


❖ MyApp is a StatelessWidget, meaning it does not hold any
state because we don’t need to update our data/widget
here.
❖ MaterialApp is used to define the app structure.
❖ The home screen is set to UserScreen() which its need to
be StatefulWidget because here we manage and update
data.
UserScreen Widget (Stateful Widget)
❖ UserScreen is a StatefulWidget because it manages
dynamic data (user list).
❖ Then we creates an instance of UserScreen which is the
UserScreenState where we will input our app logic.

UserScreenState (App logic)


❖ DatabaseHelper dbHelper: We used this to interact with
the SQLite database.
❖ List<Map<String, dynamic>> users: We also need a list
where we stores user data that we will retrieve from the
database.
❖ TextEditingController nameController &
TextEditingController ageController: We need this because
this manage input fields for name and age.
❖ int? editingUserId: Then we need to stores the ID of the
user because it will be our primary key which data being
edited.

Initializing the State


❖ When our widget was created, initState() will be called
because we will call the loadUsers() function to fetch the
data from database.
Fetching Users from SQLite
❖ We call dbHelper.getUsers() to get user
data from the database.
❖ Then by using setState() it will Updates the
users list and refreshes the UI.

Adding or Updating a User


❖ Of-course we need first to Checks if name
and age fields are not empty.
❖ Then we check if the editingUserId has a
value/data or none/null.
❖ If editingUserId is null, adds a new user
(insertUser).
❖ If editingUserId is not null, updates an
existing user (updateUser).
❖ Clears input fields and reloads user list so
that it will not retain what we typed at the
fields.
Editing a User
❖ Populates the text fields with existing user
data by retrieving it from our Map.
❖ Stores the id of the user being edited (this
will not be visible in the screen, but it
means that we are storing the same id at
editingUserId so that when we add the user
gain it will have the same id).

Deleting a User
❖ We need to Calls deleteUser(id) from
DatabaseHelper to remove the user by
using the users id.
❖ And then reloads the user list so that it will
update the users inside or list.
Building the UI
❖ Uses Scaffold to create a basic layout with an AppBar, TextField for name input and TextField for age input (we use numeric keyboard for
this), ElevatedButton for add or update users, Uses ListView.builder to display the list of users dynamically, and IconButton for our edit and
delete.

Last Step: Run you project application by using the command: flutter run
THANK YOU ☺

RYAN FERMO

You might also like