Lab Task 11
Lab Task 11
>>
<<Come to the lab with your smartphone and USB cable.>>
Task 11:
Topic: Using SQLite database
Objective: This lab task is to exercise on data storage in flutter. For now, we use SQLite database. SQLite
is a lightweight database engine that provides a relational database management system in a small and
efficient package.
To do this task follow steps bellow
His task is based on previous task
We are going to store student data to student table using SQLite database
First open new VSC window and create flutter project with the name student_info.
Open other new VSC window and opn previous task 10 student applications.
Copy screens, forms and side_menu folder from lib directory in task 10 student application to new
created student_info application lib directory.
Create folder with name “database” lib directory of student_info application
Inside it add to dart file database_helper.dart and student_model.dart.
Create student_list.dart in screens folder
Add sqflite and path dependency in pubspec.yaml
Run flutter pub get on terminal
For every screen fix the problem related to import path.
63
Task 10 Student application Current Student_info application
class Student {
int? id;
String firstName;
String lastName;
String email;
String phone;
String department;
Student({
this.id,
64
required this.firstName,
required this.lastName,
required this.email,
required this.phone,
required this.department,
});
import 'dart:async';
import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart';
import 'package:student_info/database/student_model.dart';
class DatabaseHelper {
static final DatabaseHelper instance =
DatabaseHelper._instance();
static Database? _db;
DatabaseHelper._instance();
String studentTable = 'student_table';
String colId = 'id';
String colFirstName = 'first_name';
String colLastName = 'last_name';
String colEmail = 'email';
String colPhone = 'phone';
String colDepartment = 'department';
66
return await openDatabase(
path,
version: 1,
onCreate: _createDb,
);
}
void _createDb(Database db, int version) async {
await db.execute(
'''
CREATE TABLE $studentTable(
$colId INTEGER PRIMARY KEY AUTOINCREMENT,
$colFirstName TEXT,
$colLastName TEXT,
$colEmail TEXT,
$colPhone TEXT,
$colDepartment TEXT
)
''',
);
}
Future<int> insertStudent(Map<String, dynamic> student)
async {
Database db = await this.db;
return await db.insert(studentTable, student);
}
Future<List<Student>> getStudentList() async {
Database db = await this.db;
final List<Map<String, dynamic>> maps = await
db.query(studentTable);
68
return List.generate(maps.length, (i) {
return Student.fromMap(maps[i]);
});
}
}
The DatabaseHelper class in the above code is designed to manage the creation and operations of an SQLite
database with the name of school_of_compuing for storing student information. It utilizes the sqflite
package to handle database interactions. The class follows a singleton pattern, ensuring only one instance
is created. The key components include initializing the database, defining the schema, and performing
CRUD operations. The _initDb function initializes the database by creating a student_table with columns
for id, first_name, last_name, email, phone, and department. CRUD operations are implemented through
various methods: insertStudent adds new student records, getStudentList retrieves all student records,
updateStudent modifies existing records, and deleteStudent removes records based on the id. Additionally,
the getStudentsByDepartment method fetches student records filtered by department. These methods ensure
efficient data management and retrieval, facilitating seamless interaction between the application and the
database.
Next modify add_student.dart in forms folder
import 'package:flutter/material.dart';
import
'package:student_info/screens/button_decore.dart';
import
'package:student_info/database/database_helper.dart';
import
'package:student_info/database/student_model.dart';
74
75
View inserted data
student_list.dart
import 'package:flutter/material.dart';
import
'package:student_info/database/database_helper.dart';
import
'package:student_info/database/student_model.dart';
import
'package:student_info/side_menu/floating_action_button.d
art';
@override
void initState() {
super.initState();
studentList =
DatabaseHelper.instance.getStudentList(); //
Fetch all students
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('All Students')),
body: FutureBuilder<List<Student>>(
future: studentList,
builder: (context, snapshot) {
if (snapshot.connectionState ==
ConnectionState.waiting) {
return Center(child:
CircularProgressIndicator());
} else if (snapshot.hasError) {
return Center(child: Text('Error:
${snapshot.error}'));
} else if (!snapshot.hasData ||
snapshot.data!.isEmpty) {
return Center(child: Text('No students
found.'));
} else {
return ListView.builder(
itemCount: snapshot.data!.length,
itemBuilder: (context, index) {
Student student = snapshot.data![index];
return Card(
margin: EdgeInsets.all(10.0),
77
shape: RoundedRectangleBorder(
borderRadius:
BorderRadius.circular(15.0),
),
elevation: 5,
shadowColor: Colors.teal,
child: Padding(
padding: EdgeInsets.all(10.0),
child: Column(
crossAxisAlignment:
CrossAxisAlignment.start,
children: [
Text('Department:
${student.department}',
style: TextStyle(
fontSize: 14, fontWeight:
FontWeight.bold)),
SizedBox(height: 5),
Text('First Name:
${student.firstName}',
style: TextStyle(fontSize: 14)),
Text('Last Name: ${student.lastName}',
style: TextStyle(fontSize: 14)),
Text('Email: ${student.email}',
style: TextStyle(fontSize: 14)),
Text('Phone: ${student.phone}',
style: TextStyle(fontSize: 14)),
],
),
),
);
78
},
);
}
},
),
floatingActionButton:
Custom_FloatingActionButton(), //to add new student
);
}
}
modify home.dart
import 'package:flutter/material.dart';
import
'package:student_info/screens/custom_app_bar.dart';
import 'package:student_info/side_menu/nav_bar.dart';
import 'package:student_info/screens/student_list.dart';
@override
Widget build(BuildContext context) {
return Scaffold(
drawer: const NavBar(),
appBar: CustomAppBar(context, "Home page"),
body: StudentListScreen());
}
}
79
insert some data and refresh the home page
our next task is adding update and delete opration or every student
before his code add the method that handle our update
@override
Widget build(BuildContext context)
80
new code to add
////for update
void _showUpdateForm(BuildContext context, Student
student) {
final _formKey = GlobalKey<FormState>();
final TextEditingController _firstNameController =
TextEditingController(text: student.firstName);
final TextEditingController _lastNameController =
TextEditingController(text: student.lastName);
final TextEditingController _emailController =
TextEditingController(text: student.email);
final TextEditingController _phoneController =
TextEditingController(text: student.phone);
String? _selectedDepartment = student.department;
showDialog(
context: context,
builder: (BuildContext context) {
return StatefulBuilder(
builder: (context, setState) {
return AlertDialog(
title: Text('Update Student'),
content: SingleChildScrollView(
child: Form(
key: _formKey,
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
DropdownButtonFormField<String>(
decoration:
81
InputDecoration(labelText:
'Select Department'),
value: _selectedDepartment,
items: [
DropdownMenuItem(
value: 'Computer Science',
child: Text('Computer
Science')),
DropdownMenuItem(
value: 'Information
Technology',
child: Text('Information
Technology')),
DropdownMenuItem(
value: 'Software
Engineering',
child: Text('Software
Engineering')),
],
onChanged: (value) {
setState(() {
_selectedDepartment = value;
});
},
validator: (value) =>
value == null ? 'Please
select a department' : null,
),
TextFormField(
controller:
_firstNameController,
82
decoration:
InputDecoration(labelText: 'First Name'),
validator: (value) =>
value!.isEmpty ? 'Please
enter first name' : null,
),
TextFormField(
controller: _lastNameController,
decoration:
InputDecoration(labelText: 'Last Name'),
validator: (value) =>
value!.isEmpty ? 'Please
enter last name' : null,
),
TextFormField(
controller: _emailController,
decoration:
InputDecoration(labelText: 'Email'),
keyboardType:
TextInputType.emailAddress,
validator: (value) =>
value!.isEmpty ? 'Please
enter email' : null,
),
TextFormField(
controller: _phoneController,
decoration:
InputDecoration(labelText: 'Phone'),
keyboardType:
TextInputType.phone,
validator: (value) =>
83
value!.isEmpty ? 'Please
enter phone number' : null,
),
],
),
),
),
actions: <Widget>[
TextButton(
child: Text('Cancel'),
onPressed: () {
Navigator.of(context).pop();
},
),
TextButton(
child: Text('Update'),
onPressed: () {
if
(_formKey.currentState!.validate()) {
// Update the student information
Student updatedStudent = Student(
id: student.id,
firstName:
_firstNameController.text,
lastName:
_lastNameController.text,
email: _emailController.text,
phone: _phoneController.text,
department:
_selectedDepartment!,
);
84
DatabaseHelper.instance
.updateStudent(updatedStudent.
toMap());
_refreshStudentList();
Navigator.of(context).pop();
}
},
),
],
);
},
);
},
);
}
///for update
next to this add two button “update” and “delete” with horizontal layout next to phone child
Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
TextButton.icon(
icon: Icon(Icons.edit,
color: Colors.blue), // Adding update icon
label: Text('Update',
style: TextStyle(color: Colors.blue)),
onPressed: () {
},
style: TextButton.styleFrom(
foregroundColor: Colors.blue, // Text and icon color
85
padding: EdgeInsets.symmetric(
horizontal: 20.0, vertical: 10.0),
textStyle: TextStyle(fontSize: 16),
),
),
TextButton.icon(
icon: Icon(Icons.delete,
color: Colors.red), // Adding delete
icon
style: TextStyle(color: Colors.red)),
onPressed: () {
DatabaseHelper.instance
.deleteStudent(student.id!);
_refreshStudentList();
},
style: TextButton.styleFrom(
.redAccent, // Primary color for the
button
padding: EdgeInsets.symmetric(
horizontal: 20.0, vertical: 10.0),
textStyle: TextStyle(fontSize: 16),
),
)
],
),
86
Exercise: in the above example we select all school of computing student and displayed all in home
page. Here u r requested to show every student to the corresponding department.
Hint: the method to select by specific department is already defined in database_helper.dart with the
name of getStudentsByDepartment(String department).
87
Example for computer science.
Happy codding !!
88