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

Code With Explain X Example NBR

The document provides a comprehensive guide on performing CRUD operations in Flutter using various databases such as SQLite, Hive, ObjectBox, and Firebase Firestore. It includes setup instructions, example code, and explanations for creating, reading, updating, and deleting data. Additionally, it covers the use of REST APIs for server communication in Flutter applications.

Uploaded by

rahman15-5755
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Code With Explain X Example NBR

The document provides a comprehensive guide on performing CRUD operations in Flutter using various databases such as SQLite, Hive, ObjectBox, and Firebase Firestore. It includes setup instructions, example code, and explanations for creating, reading, updating, and deleting data. Additionally, it covers the use of REST APIs for server communication in Flutter applications.

Uploaded by

rahman15-5755
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 22

Code With Explain And Example

CRUD Operations in Flutter


What is CRUD?


CRUD stands for:​


Create → Add new data​


Read → Get data​


Update → Change existing data​
Delete → Remove data
BR
Imagine we are making a contact list app where we can add, view, update, and delete
people’s information. To do this, we use a database called SQLite in Flutter.

Step 1: Setting Up SQLite in Flutter


Before using a database, we need to install the required packages.​
Open your pubspec.yaml file and add:

dependencies:
sqflite: any
path_provider: any
N
Then, run this command to install them:

flutter pub get

✅ Why do we need sqflite? → It helps us use SQLite (a database) in Flutter.​


✅ Why do we need path_provider? → It helps us find a place to store the database file.
Step 2: Creating the Database
We need to create a database where we will store information.

Code:
import 'package:sqflite/sqflite.dart';
import 'package:path/path.dart';

Future<Database> getDatabase() async {


final path = join(await getDatabasesPath(), "contacts.db");

return openDatabase(
path, BR
version: 1,
onCreate: (db, version) {
db.execute('''
CREATE TABLE contacts (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT,
phone TEXT
)
''');
},
);
}
N
Explanation:

1.​ getDatabase() → Function to create and open the database.


2.​ join(await getDatabasesPath(), "contacts.db") → Creates a file named
contacts.db to store data.
3.​ openDatabase() → Opens the database.
4.​ Inside onCreate, we write:
○​ CREATE TABLE contacts (...) → This creates a table named contacts.
○​ The table has three columns:
■​ id (number, increases automatically)
■​ name (text, stores the person's name)
■​ phone (text, stores the phone number)
Step 3: Performing CRUD Operations
Now, let's Create, Read, Update, and Delete data.

A. CREATE (Insert Data)

Adding a new contact (person) to the database.

Code:
Future<void> insertContact(Database db, String name, String phone) async {
await db.insert(
'contacts',
{'name': name, 'phone': phone},

}
);

Explanation:
BR
conflictAlgorithm: ConflictAlgorithm.replace,

1.​ insertContact(db, "Alice", "12345") → Adds Alice with phone number


12345.
2.​ db.insert('contacts', {'name': name, 'phone': phone}) → Adds data to
the contacts table.
3.​ ConflictAlgorithm.replace → If the name already exists, it will replace the old
data.

✅ Example Use:
N
await insertContact(db, "Alice", "12345");

await insertContact(db, "Bob", "67890");

Result:

id Name Phon
e

1 Alice 12345

2 Bob 67890
B. READ (Query Data)

Getting all contacts from the database.

Code:
Future<List<Map<String, dynamic>>> getContacts(Database db) async {
return await db.query('contacts');
}

Explanation:

1.​ db.query('contacts') → Gets all contacts stored in the database.


2.​ Returns a list containing all stored names and phone numbers.
BR
✅ Example Use:
List<Map<String, dynamic>> contacts = await getContacts(db);
print(contacts);

✅ Output:
[
{id: 1, name: Alice, phone: 12345},
{id: 2, name: Bob, phone: 67890}
]This shows all saved contacts.
N
C. UPDATE (Modify Data)

Changing someone's phone number.

Code:
Future<void> updateContact(Database db, String name, String newPhone) async {
await db.update(
'contacts',
{'phone': newPhone},
where: 'name = ?',
whereArgs: [name],
);
}
Explanation:

1.​ updateContact(db, "Alice", "54321") → Changes Alice's phone number to


54321.
2.​ db.update('contacts', {'phone': newPhone}) → Updates phone in the table.
3.​ where: 'name = ?' → Finds Alice.
4.​ whereArgs: [name] → Uses "Alice" as the target.

✅ Example Use:
await updateContact(db, "Alice", "54321");

Updated Database:

id

2
Name

Alice

Bob
BR
Phon
e

54321

67890

D. DELETE (Remove Data)

Removing someone from the contact list.

Code:
N
Future<void> deleteContact(Database db, String name) async {
await db.delete(
'contacts',
where: 'name = ?',
whereArgs: [name],
);
}

Explanation:

1.​ deleteContact(db, "Alice") → Removes Alice from the list.


2.​ db.delete('contacts') → Deletes data.
3.​ where: 'name = ?' → Finds the correct contact.
4.​ whereArgs: [name] → Uses "Alice" as the target.
✅ Example Use:
await deleteContact(db, "Alice");

✅ Final Database:
id Name Phon
e

2 Bob 67890

Summary
Operation

Create

Read
BR Purpose

Insert new
data

Get all data


Example Code

await insertContact(db, "Alice", "12345");

List<Map<String, dynamic>> contacts = await


getContacts(db);

Update Modify data await updateContact(db, "Alice", "54321");

Delete Remove data await deleteContact(db, "Alice");


N
What is Hive?

Hive is a NoSQL database that stores data as key-value pairs (like a dictionary). It is:​


Fast → Works quickly​


Lightweight → Uses less memory​
Good for offline storage → Saves data on your phone, even without the internet

Imagine Hive as a box where you can put and get things using a label (key).

Step 1: Setting Up Hive in Flutter


BR
Before using Hive, install the required package.

1️⃣ Open your pubspec.yaml file and add:

dependencies:
hive: any
hive_flutter: any

2️⃣ Then, run this command in the terminal:

flutter pub get

✅ Why do we need hive? → To use Hive database in Flutter​


✅ Why do we need hive_flutter? → To initialize Hive properly in a Flutter app
N
Step 2: Opening a Hive Box
Before using Hive, we need to open a box (storage space).

Code:
var box = await Hive.openBox('myBox');
Explanation:

📦 openBox('myBox') → Creates or opens a box named "myBox" to store data.


Think of it as opening a container where we will keep our data.

Step 3: Performing CRUD Operations


A. CREATE (Insert Data)

Adding a name to Hive.

Code:
BR
box.put('name', 'Alice');

Explanation:

🔹 put('name', 'Alice') → Saves "Alice" with the key 'name'.​


🔹 Now, the box contains:
{name: Alice}

✅ Example Use:
N
await box.put('name', 'Alice');

B. READ (Query Data)

Getting the saved name from Hive.

Code:
var name = box.get('name');
print(name); // Output: Alice
Explanation:

🔹 get('name') → Retrieves the value stored with the key 'name'.​


🔹 It finds "Alice" and returns it.
✅ Example Output:
Alice

C. UPDATE (Modify Data)

Changing the name from "Alice" to "Bob".

Code:
BR
box.put('name', 'Bob');

Explanation:

🔹 put('name', 'Bob') → Replaces the old value ("Alice") with "Bob".​


🔹 Now, the box contains:
{name: Bob}

✅ Example Use:
N
await box.put('name', 'Bob');

D. DELETE (Remove Data)

Removing the saved name from Hive.

Code:
box.delete('name');
Explanation:

🔹 delete('name') → Removes the 'name' key and its value.​


🔹 Now, the box is empty:
{}

✅ Example Use:
await box.delete('name');

Summary BR
Operation Purpose Example Code

Create Insert new data await box.put('name',


'Alice');

Read Get stored data var name =


box.get('name');

Update Change existing await box.put('name',


data 'Bob');

Delete Remove data await box.delete('name');


N
What is ObjectBox?
ObjectBox is a high-performance NoSQL database optimized for mobile devices. It is faster
than SQLite and Hive because it stores data as objects (instead of tables or key-value pairs).

Imagine ObjectBox as a storage system where you store objects (like your User object) instead
of just data in tables. It's super fast and works well for apps on mobile devices.

Step 1: Setting Up ObjectBox in Flutter


BR
Before using ObjectBox, install the required package.

1️⃣ Open your pubspec.yaml file and add:

dependencies:
objectbox: any

2️⃣ Then, run this command in the terminal:

flutter pub get


N
Step 2: Creating a Box
Before using ObjectBox, you need to create a box (a storage space). In this case, we will create
a User box.

Code:
var box = store.box<User>();

Explanation:

🔹 box() → Creates or opens a User box where we will store user data (like name and age).
Now, you have a place where you can store your user data as objects (not just rows of data).
Step 3: Performing CRUD Operations
A. CREATE (Insert Data)

Adding a User to the database.

Code:
box.put(User(name: 'Alice', age: 25));

Explanation:

🔹 put(User(name: 'Alice', age: 25)) → Adds a new User object with the name "Alice" and
BR
🔹 This will save the User as an object in the database, not just text or numbers.
age 25 to the box.​

✅ Example Use:
await box.put(User(name: 'Alice', age: 25));

B. READ (Query Data)

Getting a User by ID from the database.

Code:
N
var user = box.get(1); // Get user by ID
print(user?.name); // Output: Alice

Explanation:

🔹 get(1) → Retrieves the User object with ID 1.​


🔹 user?.name → If the user exists, print their name (e.g., "Alice"). The ?. is used to avoid
errors if the user doesn’t exist.

✅ Example Output:
Alice
C. UPDATE (Modify Data)

Changing a User's age.

Code:
var user = box.get(1);
if (user != null) {
user.age = 26; // Update age
box.put(user); // Save updated user
}

Explanation:

🔹 get(1) → Retrieves the User object with ID 1.​


🔹 user.age = 26 → Updates the age to 26.​
🔹 put(user) → Saves the updated User object back into the database.
BR
✅ Example Use:
await box.put(User(name: 'Alice', age: 25));
var user = box.get(1);
if (user != null) {
user.age = 26;
await box.put(user);
}

D. DELETE (Remove Data)


N
Removing a User by ID.

Code:
box.remove(1); // Remove user by ID

Explanation:

🔹 remove(1) → Removes the User object with ID 1 from the box.​


🔹 The user data is completely deleted from the database.
✅ Example Use:
await box.remove(1);

Summary
Operation Purpose Example Code

Create Insert new data await box.put(User(name: 'Alice',


age: 25));

Read Get data by ID var user = box.get(1);


print(user?.name);

Update Modify existing data user.age = 26; await box.put(user);

Delete
BR Remove data by ID await box.remove(1);
N
What is Firebase Firestore?
Firebase Firestore is a cloud-based NoSQL database that stores data and syncs it in
real-time. It’s perfect for apps with multiple users because data changes automatically across all
devices in real-time.

Step 1: Setting Up Firebase Firestore in Flutter


Before using Firebase Firestore, you need to set it up in your Flutter project.

BR
1️⃣ Add Firebase to your Flutter project (via Firebase Console). 2️⃣ Install the Firestore
package. Open your pubspec.yaml file and add the following dependency:

dependencies:
cloud_firestore: ^4.0.0

3️⃣ Then, run this command in the terminal to install it:

flutter pub get

Step 2: Performing CRUD Operations


N
A. CREATE (Insert Data)

Adding new data to the users collection in Firestore.

Code:
FirebaseFirestore.instance
.collection('users')
.add({'name': 'Alice', 'age': 25});
Explanation:

🔹 collection('users') → Refers to the users collection in Firestore where the data will be
🔹 add({'name': 'Alice', 'age': 25}) → Adds a new document with the name "Alice" and age
saved.​

25. Firestore automatically generates a unique ID for this document.

✅ Example Use:
await FirebaseFirestore.instance.collection('users').add({
'name': 'Alice',
'age': 25,
});

BR
B. READ (Query Data)

Retrieving all documents (users) from the users collection.

Code:
var snapshot = await FirebaseFirestore.instance.collection('users').get();
snapshot.docs.forEach((doc) {
print(doc.data()); // Output: Map of user data
});
N
Explanation:

🔹 get() → Retrieves all the documents from the users collection.​


🔹 snapshot.docs.forEach() → Iterates through each document and prints the data (name,
age, etc.).

✅ Example Output:
{name: Alice, age: 25}
{name: Bob, age: 30}

C. UPDATE (Modify Data)

Updating an existing document in the users collection.


Code:
FirebaseFirestore.instance
.collection('users')
.doc('documentId') // The document ID you want to update
.update({'age': 26});

Explanation:

🔹 doc('documentId') → Specifies the document to update by its ID.​


🔹 update({'age': 26}) → Updates the age field to 26 in that specific document.
✅ Example Use:
await FirebaseFirestore.instance.collection('users').doc('userID123').update({
'age': 26,
});
BR
D. DELETE (Remove Data)

Deleting a document by its ID.

Code:
FirebaseFirestore.instance
.collection('users')
.doc('documentId') // The document ID you want to delete
.delete();
N
Explanation:

🔹 doc('documentId') → Specifies the document to delete by its ID.​


🔹 delete() → Removes the document from the users collection.
✅ Example Use:
await FirebaseFirestore.instance.collection('users').doc('userID123').delete();
Summary
Operati Purpo Example Code
on se

Create Insert await


new FirebaseFirestore.instance.collection('users').add({'n
data ame': 'Alice', 'age': 25});

Read Get all var snapshot = await


data FirebaseFirestore.instance.collection('users').get();
snapshot.docs.forEach((doc) { print(doc.data()); });

Update

Delete
BR
Modify
data
await
FirebaseFirestore.instance.collection('users').doc('us
erID123').update({'age': 26});

Remov await
e data FirebaseFirestore.instance.collection('users').doc('us
erID123').delete();
N
What is a REST API?
A REST API (Representational State Transfer) is a way for your app to communicate with an
external server using HTTP methods (POST, GET, PUT, DELETE). Data is usually transferred in
a format like JSON.

Step 1: Setting Up HTTP Package in Flutter


Before using REST APIs in your Flutter app, you need to install the http package.

BR
1️⃣ Open your pubspec.yaml file and add the following dependency:

dependencies:

http: ^0.15.0

2️⃣ Run this command in your terminal to install the package:

flutter pub get


N
Step 2: Performing CRUD Operations with REST API
A. CREATE (POST Request)

Sending data to the server to create a new resource (like a new user).

Code:

var response = await http.post(

Uri.parse('https://example.com/api/users'),

body: {'name': 'Alice', 'age': '25'},


);

print(response.body); // Output: Response from the server

Explanation:

🔹 http.post() → Sends a POST request to the server to create a new resource.​


🔹 Uri.parse('https://example.com/api/users') → Specifies the server URL and endpoint.​
🔹 body: {'name': 'Alice', 'age': '25'} → Sends the user data in JSON format to the server.
✅ Example Use:
await http.post(

Uri.parse('https://example.com/api/users'),
BR
body: {'name': 'Alice', 'age': '25'},

);

B. READ (GET Request)

Retrieving data from the server (like a list of users).

Code:
N
var response = await http.get(Uri.parse('https://example.com/api/users'));

print(response.body); // Output: List of users in JSON format

Explanation:

🔹 http.get() → Sends a GET request to the server to retrieve data.​


🔹 Uri.parse('https://example.com/api/users') → Specifies the server URL and endpoint to
fetch data from.

✅ Example Use:
await http.get(Uri.parse('https://example.com/api/users'));
C. UPDATE (PUT/PATCH Request)

Sending updated data to the server to modify an existing resource.

Code:

var response = await http.put(

Uri.parse('https://example.com/api/users/1'),

body: {'name': 'Alice', 'age': '26'},

);

print(response.body); // Output: Updated user data

Explanation:
BR
🔹 http.put() → Sends a PUT request to update an existing resource.​
🔹 Uri.parse('https://example.com/api/users/1') → Specifies the server URL with the ID of
🔹 body: {'name': 'Alice', 'age': '26'} → Sends the updated data for that user.
the user you want to update.​

✅ Example Use:
await http.put(
N
Uri.parse('https://example.com/api/users/1'),

body: {'name': 'Alice', 'age': '26'},

);

D. DELETE (DELETE Request)

Sending a request to the server to remove a resource.

Code:

var response = await http.delete(

Uri.parse('https://example.com/api/users/1'),
);

print(response.body); // Output: Success or error message

Explanation:

🔹 http.delete() → Sends a DELETE request to remove a resource from the server.​


🔹 Uri.parse('https://example.com/api/users/1') → Specifies the server URL and the ID of
the user to delete.

✅ Example Use:
await http.delete(Uri.parse('https://example.com/api/users/1'));

Summary of CRUD Operations

Database

SQLite
BR Create

db.insert()
Read

db.query()
Update

db.update()
Delete

db.delete()

Hive box.put() box.get() box.put() (overwrite) box.delete()

ObjectBox box.put() box.get() box.put() (overwrite) box.remove()


N
Firebase collection.add() collection.get() doc.update() doc.delete()
Firestore

REST API http.post() http.get() http.put() http.delete()

-​ TANVIR NIBIR

You might also like