0% found this document useful (0 votes)
8 views7 pages

LAB8

The document outlines a lab exercise focused on using SharePreference and SQLite for data storage in Flutter applications. It includes practical exercises for creating a notes app that utilizes SharePreference for storing notes and a student management app that employs SQLite for managing student data. The document provides code snippets and explanations for implementing these functionalities.

Uploaded by

thaico0915
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)
8 views7 pages

LAB8

The document outlines a lab exercise focused on using SharePreference and SQLite for data storage in Flutter applications. It includes practical exercises for creating a notes app that utilizes SharePreference for storing notes and a student management app that employs SQLite for managing student data. The document provides code snippets and explanations for implementing these functionalities.

Uploaded by

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

LAB 8

SHAREPREFERENCE
MỤC TIÊU
Sau khi sinh viên hoàn thành các yêu cầu của buổi học này, sinh viên có thể:
1. Biết cách sử dụng SharePreference để lưu trữ thông tin cơ bản
2. Áp dụng SQLite trong lưu trữ dữ liệu
Bài tập thực hành 1: Xây dựng ứng dụng như sau:

import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'dart:convert';

void main() {
runApp(const MyApp());
}

class MyApp extends StatelessWidget {


const MyApp({super.key});

@override
Widget build(BuildContext context) {
return const MaterialApp(
debugShowCheckedModeBanner: false,
home: NotesPage(),
);
}
}
class NotesPage extends StatefulWidget {
const NotesPage({super.key});

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

class NotesPageState extends State<NotesPage> {


List<String> notes = [];
TextEditingController controllerNote = TextEditingController();

@override
void initState() {
super.initState();
loadNotes();
}

Future<void> loadNotes() async {


SharedPreferences prefs = await SharedPreferences.getInstance();
setState(() {
notes = (prefs.getStringList('notes') ?? []);
});
}

Future<void> saveNotes() async {


SharedPreferences prefs = await SharedPreferences.getInstance();
await prefs.setStringList('notes', notes);
}

void addNote() {
if (controllerNote.text.isNotEmpty) {
setState(() {
notes.add(controllerNote.text);
controllerNote.clear();
});
saveNotes();
}
}

void deleteNote(int index) {


setState(() {
notes.removeAt(index);
});
saveNotes();
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("Notes App",style: TextStyle(color: Colors.white),),
backgroundColor: Colors.pink,
),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
children: [
TextField(
controller: controllerNote,
decoration: const InputDecoration(labelText: "Enter your note"),
),
const SizedBox(height: 10),
ElevatedButton(
onPressed: addNote,
child: const Text("Add Note"),
),
const SizedBox(height: 20),
Expanded(
child: ListView.builder(
itemCount: notes.length,
itemBuilder: (context, index) {
return Card(
child: ListTile(
title: Text(notes[index]),
trailing: IconButton(
icon: const Icon(Icons.delete, color: Colors.red),
onPressed: () => deleteNote(index),
),
),
);
},
),
),
],
),
),
);
}
}

Bài tập thực hành 2: Sử dụng SQLite xây dựng app quản lý sinh viên như hình dưới:
class Student {
int? id;
String name;
int age;
String className;

Student({this.id, required this.name, required this.age, required


this.className});

Map<String, dynamic> toMap() {


return {
'id': id,
'name': name,
'age': age,
'className': className,
};
}

factory Student.fromMap(Map<String, dynamic> map) {


return Student(
id: map['id'],
name: map['name'],
age: map['age'],
className: map['className'],
);
}
}

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

class DatabaseLib {
static final DatabaseLib instance = DatabaseLib._init();
static Database? _database;

DatabaseLib._init();

Future<Database> get database async {


if (_database != null) return _database!;
_database = await _initDB('students.db');
return _database!;
}

Future<Database> _initDB(String filePath) async {


final dbPath = await getDatabasesPath();
final path = join(dbPath, filePath);

return await openDatabase(path, version: 1, onCreate: _createDB);


}

Future<void> _createDB(Database db, int version) async {


await db.execute('''
CREATE TABLE students (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
age INTEGER NOT NULL,
className TEXT NOT NULL
)
''');
print('Bảng students đã được tạo.');
}

Future<int> addStudent(Student student) async {


final db = await instance.database;
return await db.insert('students', student.toMap());
}

Future<List<Student>> getStudents() async {


final db = await instance.database;
final result = await db.query('students');
return result.map((json) => Student.fromMap(json)).toList();
}

Future<int> updateStudent(Student student) async {


final db = await instance.database;
return await db.update('students', student.toMap(),
where: 'id = ?', whereArgs: [student.id]);
}

Future<int> deleteStudent(int id) async {


final db = await instance.database;
return await db.delete('students', where: 'id = ?', whereArgs: [id]);
}
}

import 'package:flutter/material.dart';
import 'db_helper.dart';
import 'student.dart';

void main() {
runApp(const MyApp());
}

class MyApp extends StatelessWidget {


const MyApp({super.key});

@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Quản Lý Sinh Viên',
theme: ThemeData(primarySwatch: Colors.blue),
home: const StudentScreen(),
debugShowCheckedModeBanner: false,
);
}
}

class StudentScreen extends StatefulWidget {


const StudentScreen({super.key});

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

class StudentScreenState extends State<StudentScreen> {


final TextEditingController _nameController = TextEditingController();
final TextEditingController _ageController = TextEditingController();
final TextEditingController _classController = TextEditingController();
List<Student> _students = [];
@override
void initState() {
super.initState();
_loadStudents();
}

Future<void> _loadStudents() async {


final students = await DatabaseLib.instance.getStudents();
setState(() {
_students = students;
});
}

Future<void> _addOrUpdateStudent({Student? student}) async {


String title = student == null ? 'Thêm Sinh Viên' : 'Cập Nhật Sinh Viên';
_nameController.text = student?.name ?? '';
_ageController.text = student?.age.toString() ?? '';
_classController.text = student?.className ?? '';

await showDialog(
context: context,
builder: (context) => AlertDialog(
title: Text(title),
content: Column(
mainAxisSize: MainAxisSize.min,
children: [
TextField(controller: _nameController, decoration: const
InputDecoration(labelText: 'Tên')),
TextField(controller: _ageController, decoration: const
InputDecoration(labelText: 'Tuổi'), keyboardType: TextInputType.number),
TextField(controller: _classController, decoration: const
InputDecoration(labelText: 'Lớp')),
],
),
actions: [
TextButton(
child: const Text('Hủy'),
onPressed: () => Navigator.pop(context),
),
ElevatedButton(
child: Text(student == null ? 'Thêm' : 'Cập Nhật'),
onPressed: () async {
if (_nameController.text.isEmpty || _ageController.text.isEmpty ||
_classController.text.isEmpty) return;
final newStudent = Student(
id: student?.id,
name: _nameController.text,
age: int.parse(_ageController.text),
className: _classController.text,
);
if (student == null) {
await DatabaseLib.instance.addStudent(newStudent);
} else {
await DatabaseLib.instance.updateStudent(newStudent);
}
Navigator.pop(context);
_loadStudents();
},
),
],
),
);
}

Future<void> _deleteStudent(int id) async {


await DatabaseLib.instance.deleteStudent(id);
_loadStudents();
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Quản Lý Sinh Viên',style: TextStyle(color:
Colors.white),),
backgroundColor: Colors.pink,
),
body: Column(
children: [
Expanded(
child: ListView.builder(
itemCount: _students.length,
itemBuilder: (context, index) {
final student = _students[index];
return ListTile(
title: Text('${student.name} - ${student.className}'),
subtitle: Text('Tuổi: ${student.age}'),
trailing: Row(
mainAxisSize: MainAxisSize.min,
children: [
IconButton(icon: const Icon(Icons.edit, color:
Colors.blue), onPressed: () => _addOrUpdateStudent(student: student)),
IconButton(icon: const Icon(Icons.delete, color:
Colors.red), onPressed: () => _deleteStudent(student.id!)),
],
),
);
},
),
),
],
),
floatingActionButton: FloatingActionButton(
child: const Icon(Icons.add),
onPressed: () => _addOrUpdateStudent(),
),
);
}
}

You might also like