Sqflite Database (CRUD Operation Simple) Data Delete Functionality in List in Flutter

import "package:flutter/material.dart";
import "package:sqflite/sqflite.dart";
import "package:path/path.dart";

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

class MyApp extends StatelessWidget {
const MyApp({super.key});

@override
Widget build(BuildContext context) {
return MaterialApp(
title: "Sqflite Database",
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.grey,
),
home: const HomeScreen3(),
);
}
}

class HomeScreen3 extends StatefulWidget {
const HomeScreen3({super.key});

@override
State<HomeScreen3> createState() {
return HomeScreen3State();
}
}

class HomeScreen3State extends State<HomeScreen3> {
TextEditingController controller = TextEditingController();
final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
Future<Database>? database;

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

/// Initializing Database
Future<void> _initializeDatabase() async {
database = openDatabase(
join(await getDatabasesPath(), "mydb3.db"),
onCreate: (db, version) {
return db.execute(
"CREATE TABLE USER3(ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT)");
},
version: 1,
);
}

Future<void> insert(String name) async {
final Database database = await openDatabase(
join(await getDatabasesPath(), "mydb3.db"),
);
database.insert(
"USER3",
{
"NAME": name,
},
conflictAlgorithm: ConflictAlgorithm.replace,
);
}

@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: () {
return FocusManager.instance.primaryFocus?.unfocus();
},
child: Scaffold(
appBar: AppBar(
title: const Text("Sqflite Database"),
centerTitle: true,
backgroundColor: Colors.grey,
),
body: Center(
child: Form(
key: _formKey,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
SizedBox(
width: 300.0,
child: TextFormField(
controller: controller,
validator: (value) {
if (value!.isEmpty) {
return "Please enter the text";
}
return null;
},
decoration: InputDecoration(
hintText: "Enter the text",
labelText: "Text",
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(11.0),
),
),
),
),
const SizedBox(height: 40.0),
ElevatedButton(
onPressed: () {
if (_formKey.currentState!.validate()) {
insert(controller.text);
controller.clear();
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text("Data Saved"),
duration: Duration(seconds: 2),
),
);
Navigator.push(
context,
MaterialPageRoute(
builder: (context) {
return DisplayData3();
},
),
);
}
},
style: ElevatedButton.styleFrom(
fixedSize: const Size(200.0, 50.0),
backgroundColor: Colors.blue,
),
child: const Text(
"SAVE",
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 20.0,
color: Colors.white),
),
),
],
),
),
),
),
);
}
}

class DisplayData3 extends StatefulWidget {
const DisplayData3({super.key});

@override
State<DisplayData3> createState() {
return DisplayData3State();
}
}

class DisplayData3State extends State<DisplayData3> {
Future<List<Map<String, dynamic>>>? userdata;
Future<Database>? database;

Future<List<Map<String, dynamic>>> getUserData() async {
final Database database = await openDatabase(
join(await getDatabasesPath(), "mydb3.db"),
);
final List<Map<String, dynamic>> maps = await database.query("USER3");
return maps;
}

Future<void> updateData(int userId, String updatedName) async {
final Database database = await openDatabase(
join(
await getDatabasesPath(),
),
);
await database.update(
"USER3",
{
"NAME": updatedName,
},
where: "ID = ?",
whereArgs: [userId],
);
setState(
() {
userdata = getUserData();
print("Updated data : $userdata");
},
);
}

/// Initializing Database
Future<void> initializeDatabase() async {
database = openDatabase(
join(await getDatabasesPath(), "mydb3.db"),
onCreate: (db, version) {
return db.execute(
"CREATE TABLE USER3(ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT)");
},
version: 1,
);
}

/// For Delete data
Future<void> deleteData(int id) async {
final Database database = await openDatabase(
join(await getDatabasesPath(), "mydb3.db"),
);
database.delete(
"USER3",
where: "ID = ?",
whereArgs: [id],
);
setState(
() {
userdata = getUserData();
},
);
}

@override
void initState() {
super.initState();
userdata = getUserData();
initializeDatabase();
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text(
"Sqflite data delete functionality",
style: TextStyle(fontWeight: FontWeight.bold),
),
centerTitle: true,
backgroundColor: Colors.grey,
),
body: FutureBuilder(
future: userdata,
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return const Center(
child: CircularProgressIndicator(),
);
} else if (snapshot.hasError) {
return Center(
child: Text("Error : ${snapshot.error}"),
);
} else if (!snapshot.hasData || snapshot.data!.isEmpty) {
return const Center(
child: Text(
"No data available!",
style: TextStyle(fontWeight: FontWeight.bold, fontSize: 20.0),
),
);
} else {
return ListView.builder(
itemCount: snapshot.data!.length,
itemBuilder: (context, index) {
return Card(
child: ListTile(
leading:
CircleAvatar(backgroundColor: Colors.grey.shade400),
title: Text(
snapshot.data![index]["NAME"],
style: const TextStyle(fontWeight: FontWeight.bold),
),
subtitle: Text(snapshot.data![index]["NAME"]),
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) {
return ContentPage(
title: "${snapshot.data![index]["NAME"]}",
subtitle: "${snapshot.data![index]["NAME"]}",
);
},
),
);
},
trailing: Row(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
IconButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) {
return UpdateData3(
userId: snapshot.data![index]["ID"],
currentName: snapshot.data![index]["NAME"],
onDataUpdated: () {
setState(
() {
userdata = getUserData();
},
);
},
);
},
),
);
},
icon: const Icon(Icons.edit, color: Colors.brown),
),
IconButton(
onPressed: () {
showDialog(
context: context,
builder: (context) {
return AlertDialog(
title: const Text(
"Delete data",
style:
TextStyle(fontWeight: FontWeight.bold),
),
content: const Text("Are you sure ?"),
actions: <Widget>[
TextButton(
onPressed: () {
Navigator.pop(context);
},
child: const Text(
"Cancel",
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 20.0),
),
),
TextButton(
onPressed: () {
deleteData(snapshot.data![index]["ID"]);
setState(
() {
userdata = getUserData();
},
);
Navigator.pop(context);
ScaffoldMessenger.of(context)
.showSnackBar(
SnackBar(
content: Text(
"${snapshot.data![index]["NAME"]} deleted Successfully"),
duration:
const Duration(seconds: 2),
),
);
},
child: const Text(
"Ok",
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 20.0),
),
),
],
);
},
);
},
icon: const Icon(Icons.delete, color: Colors.red),
),
],
),
),
);
},
);
}
},
),
);
}
}

class UpdateData3 extends StatefulWidget {
final int userId;
final String currentName;
final Function() onDataUpdated;

const UpdateData3(
{super.key,
required this.userId,
required this.currentName,
required this.onDataUpdated});

@override
State<UpdateData3> createState() {
return UpdateData3State();
}
}

class UpdateData3State extends State<UpdateData3> {
TextEditingController updateController = TextEditingController();
final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
Future<Database>? database;

/// Initialize Database
Future<void> initializeDatabase() async {
database = openDatabase(
join(await getDatabasesPath(), "mydb3.db"),
onCreate: (db, version) {
return db.execute(
"CREATE TABLE USER3(ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT)");
},
version: 1,
);
}

/// For Update data
Future<void> updateData(int userId, String updatedName) async {
final Database database = await openDatabase(
join(await getDatabasesPath(), "mydb3.db"),
);
database.update(
"USER3",
{
"NAME": updatedName,
},
where: "ID = ?",
whereArgs: [userId],
);
}

@override
void initState() {
super.initState();
initializeDatabase();
updateController.text = widget.currentName;
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text(
"Sqflite Database",
style: TextStyle(fontWeight: FontWeight.bold),
),
centerTitle: true,
backgroundColor: Colors.grey,
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
SizedBox(
width: 300.0,
child: TextFormField(
controller: updateController,
validator: (value) {
if (value!.isEmpty) {
return "Please enter text";
}
return null;
},
decoration: InputDecoration(
hintText: "Update the text",
labelText: "Update",
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(11.0),
),
),
),
),
const SizedBox(height: 40.0),
ElevatedButton(
onPressed: () async {
await updateData(widget.userId, updateController.text);
widget.onDataUpdated();
Navigator.pop(context);
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text("Data Updated..."),
duration: Duration(seconds: 2),
),
);
},
style: ElevatedButton.styleFrom(
backgroundColor: Colors.blue,
fixedSize: const Size(200.0, 50.0),
),
child: const Text(
"UPDATE",
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 20.0,
color: Colors.white),
),
),
],
),
),
);
}
}

class ContentPage extends StatelessWidget {
const ContentPage({super.key, required this.title, required this.subtitle});

final String title;
final String subtitle;

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(
title,
style: const TextStyle(fontWeight: FontWeight.bold),
),
centerTitle: true,
backgroundColor: Colors.grey,
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
title,
style:
const TextStyle(fontWeight: FontWeight.bold, fontSize: 40.0),
),
const SizedBox(height: 40.0),
Text(
subtitle,
style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 20.0),
),
],
),
),
);
}
}

Comments

Popular posts from this blog

Second GET API Calling with Bloc simple Example in Flutter

Stack Container Scrollable Card widget UI with Custom Widget

Pagination with Bloc Pattern in Flutter