LAB8
LAB8
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());
}
@override
Widget build(BuildContext context) {
return const MaterialApp(
debugShowCheckedModeBanner: false,
home: NotesPage(),
);
}
}
class NotesPage extends StatefulWidget {
const NotesPage({super.key});
@override
NotesPageState createState() => NotesPageState();
}
@override
void initState() {
super.initState();
loadNotes();
}
void addNote() {
if (controllerNote.text.isNotEmpty) {
setState(() {
notes.add(controllerNote.text);
controllerNote.clear();
});
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;
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();
import 'package:flutter/material.dart';
import 'db_helper.dart';
import 'student.dart';
void main() {
runApp(const MyApp());
}
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Quản Lý Sinh Viên',
theme: ThemeData(primarySwatch: Colors.blue),
home: const StudentScreen(),
debugShowCheckedModeBanner: false,
);
}
}
@override
StudentScreenState createState() => StudentScreenState();
}
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();
},
),
],
),
);
}
@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(),
),
);
}
}