0% found this document useful (0 votes)
9 views26 pages

Lab Task 11

The document outlines a lab task focused on using SQLite database for data storage in a Flutter application named 'student_info'. It provides step-by-step instructions for setting up the project, creating a student model, and implementing CRUD operations using a DatabaseHelper class. Additionally, it includes guidance on modifying forms for adding and updating student records, as well as displaying the student list in the application.

Uploaded by

yabsram94
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)
9 views26 pages

Lab Task 11

The document outlines a lab task focused on using SQLite database for data storage in a Flutter application named 'student_info'. It provides step-by-step instructions for setting up the project, creating a student model, and implementing CRUD operations using a DatabaseHelper class. Additionally, it includes guidance on modifying forms for adding and updating student records, as well as displaying the student list in the application.

Uploaded by

yabsram94
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/ 26

<<After this, you must use your phone as an emulator.

>>
<<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

 After this let’s continue


 First define the model. Pour model is student and its properties are department, fname ,lanem, email
and phone.
 student_model.dart

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,
});

// Convert a Student into a Map


Map<String, dynamic> toMap() {
return {
'id': id,
'first_name': firstName,
'last_name': lastName,
'email': email,
'phone': phone,
'department': department,
};
}

// Convert a Map into a Student


factory Student.fromMap(Map<String, dynamic> map) {
return Student(
id: map['id'],
firstName: map['first_name'],
lastName: map['last_name'],
email: map['email'],
phone: map['phone'],
department: map['department'],
);
}
}
65
 from above code there is two methds. toMap converts the Student object into a Map<String, dynamic>,
making it suitable for database operations where data is stored as key-value pairs. Conversely, fromMap
creates a student object from a map, allowing easy reconstruction of data retrieved from the database.

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';

Future<Database> get db async {


if (_db == null) {
_db = await _initDb();
}
return _db!;
}
Future<Database> _initDb() async {
final dbPath = await getDatabasesPath();
final path = join(dbPath, 'school_of_compuing.db');

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);

return List.generate(maps.length, (i) {


67
return Student.fromMap(maps[i]);
});
}
Future<int> updateStudent(Map<String, dynamic> student)
async {
Database db = await this.db;
return await db.update(
studentTable,
student,
where: '$colId = ?',
whereArgs: [student[colId]],
);
}
Future<int> deleteStudent(int id) async {
Database db = await this.db;
return await db.delete(
studentTable,
where: '$colId = ?',
whereArgs: [id],
);
}
Future<List<Student>> getStudentsByDepartment(String
department) async {
Database db = await this.db;
final List<Map<String, dynamic>> maps = await
db.query(
studentTable,
where: '$colDepartment = ?',
whereArgs: [department],
);

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';

void showAddStudentForm(BuildContext context) {


final _formKey = GlobalKey<FormState>();
final TextEditingController _firstNameController =
TextEditingController();
final TextEditingController _lastNameController =
TextEditingController();
69
final TextEditingController _emailController =
TextEditingController();
final TextEditingController _phoneController =
TextEditingController();
String? _selectedDepartment;
String _resultText = '';
showDialog(
context: context,
builder: (BuildContext context) {
return StatefulBuilder(
builder: (context, setState) {
return AlertDialog(
title: Text('Add New Student'),
content: SingleChildScrollView(
child: Form(
key: _formKey,
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
DropdownButtonFormField<String>(
decoration:
InputDecoration(labelText: 'Select Department'),
items: [
DropdownMenuItem(
value: 'Computer Science',
child: Text('Computer Science')),
DropdownMenuItem(
value: 'Information Technology',
child: Text('Information Technology')),
DropdownMenuItem(
value: 'Software Engineering',
70
child: Text('Software Engineering')),
],
onChanged: (value) {
_selectedDepartment = value;
},
validator: (value) =>
value == null ? 'Please select a department' : null,
),
TextFormField(
controller: _firstNameController,
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) =>
71
value!.isEmpty ? 'Please enter email' : null,),
TextFormField(
controller: _phoneController,
decoration:
InputDecoration(labelText: 'Phone'),
keyboardType: TextInputType.phone,
validator: (value) =>
value!.isEmpty ? 'Please enter phone number' : null,
),
SizedBox(height: 20),
Text(
_resultText,
style: TextStyle(
fontSize: 16,
color: Colors.green,
fontWeight: FontWeight.bold),
),
],
),
),
),
actions: <Widget>[
TextButton(
child: Text('Cancel'),
onPressed: () {
Navigator.of(context).pop();
},
style: customButtonStyle(),
),
TextButton(
child: Text('Clear'),
72
onPressed: () {
_firstNameController.clear();
_lastNameController.clear();
_emailController.clear();
_phoneController.clear();
setState(() {
_resultText = '';
});
},
style: customButtonStyle(),
),
TextButton(
child: Text('Add'),
onPressed: () async {
if (_formKey.currentState!.validate())
{
// Access the controller values here
Student student = Student(
firstName:
_firstNameController.text,
lastName:
_lastNameController.text,
email: _emailController.text,
phone: _phoneController.text,
department: _selectedDepartment!,
);
try {
await DatabaseHelper.instance
.insertStudent(student.toMap()
);
setState(() {
73
_resultText = 'Student added
successfully!';
});
} catch (e) {
setState(() {
_resultText = 'Failed to add
student.';
});
}
}
},
style: customButtonStyle(),
),
],
);
},
);
},
);
}

 Then try to run your application

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';

class StudentListScreen extends StatefulWidget {


@override
_StudentListScreenState createState() =>
_StudentListScreenState();
}

class _StudentListScreenState extends


State<StudentListScreen> {
late Future<List<Student>> studentList;

@override
void initState() {
super.initState();
studentList =
DatabaseHelper.instance.getStudentList(); //
Fetch all students
}

Future<void> _refreshStudentList() async {


setState(() {
76
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';

class Home extends StatelessWidget {


const Home({super.key});

@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

You might also like