Show and Update data in MySql database with Dio Library API

 import "dart:convert";

import "package:flutter/material.dart";
import "package:dio/dio.dart";

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

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

@override
Widget build(BuildContext context) {
return MaterialApp(
title: "Update data with Dio Library",
debugShowCheckedModeBanner: false,
theme: ThemeData(
appBarTheme: const AppBarTheme(
backgroundColor: Colors.grey,
centerTitle: true,
),
),
home: const UpdateDataDio(),
);
}
}

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

@override
State<UpdateDataDio> createState() {
return UpdateDataDioState();
}
}

class UpdateDataDioState extends State<UpdateDataDio> {
late Future<List<UpdateDioModel>> futureData;

@override
void initState() {
super.initState();
futureData = fetchData();
}

Future<List<UpdateDioModel>> fetchData() async {
try {
final response = await Dio().get("http://192.168.1.40/Flutter/show.php");

if (response.statusCode == 200) {
Iterable jsonResponse = jsonDecode(response.data);

List<UpdateDioModel> dataInputs = jsonResponse.map(
(model) {
return UpdateDioModel.fromJson(model);
},
).toList();
return dataInputs;
} else {
throw Exception("Failed to load data");
}
} catch (error) {
throw Exception("Failed to load data : $error");
}
}

/// Update Method to update the data in MySql database
Future<void> updateData(String id, String name, String birthDate,
String phone, String gender) async {
try {
print("Method DATA" + id + name + birthDate + phone + gender);

final formData = FormData.fromMap(
{
"id": id,
"name": name,
"birth_date": birthDate,
"phone": phone,
"gender": gender,
},
);

final response = await Dio()
.post("http://192.168.1.40/Flutter/update.php", data: formData);
print("My Response : $response");

if (response.statusCode == 200) {
setState(
() {
futureData = fetchData();
},
);
} else {
throw Exception("Failed to update data");
}
} catch (error) {
print("Error updating data : $error");
throw Exception("Failed to update data : $error");
}
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text(
"Update Data with Dio Library",
style: TextStyle(fontWeight: FontWeight.bold),
),
),
body: Center(
child: FutureBuilder<List<UpdateDioModel>>(
future: futureData,
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return const Center(
child: CircularProgressIndicator(),
);
} else if (snapshot.hasError) {
Text("${snapshot.error}");
} else if (snapshot.hasData) {
List<UpdateDioModel>? data = snapshot.data;

return ListView.builder(
itemCount: data!.length,
itemBuilder: (context, index) {
return Card(
child: ListTile(
title: Text(
data[index].name,
style: const TextStyle(fontWeight: FontWeight.bold),
),
subtitle: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(data[index].birth_date),
Text(data[index].phone),
Text(data[index].gender),
],
),
onTap: () {
showUpdateData(data[index]);
print("INDEX is ${data[index].id}");
},
),
);
},
);
}
return const CircularProgressIndicator();
},
),
),
);
}

/// Update DialogBox to update the data
Future<void> showUpdateData(UpdateDioModel dataInputs) async {
TextEditingController nameController =
TextEditingController(text: dataInputs.name);
TextEditingController birthDateController =
TextEditingController(text: dataInputs.birth_date);
TextEditingController phoneController =
TextEditingController(text: dataInputs.phone);
TextEditingController genderController =
TextEditingController(text: dataInputs.gender);

await showDialog(
context: context,
builder: (context) {
return AlertDialog(
title: const Text(
"Update data",
style: TextStyle(fontWeight: FontWeight.bold),
),
content: SingleChildScrollView(
child: ListBody(
children: <Widget>[
TextFormField(
controller: nameController,
decoration: const InputDecoration(
hintText: "Enter the name",
),
),
TextFormField(
controller: birthDateController,
decoration: const InputDecoration(
hintText: "Enter the birthdate",
),
),
TextFormField(
controller: phoneController,
maxLength: 10,
decoration: const InputDecoration(
hintText: "Enter the phone number",
),
),
TextFormField(
controller: genderController,
decoration: const InputDecoration(
hintText: "Enter the gender",
),
),
],
),
),
actions: <Widget>[
TextButton(
onPressed: () {
String name = nameController.text;
String birthDate = birthDateController.text;
String phone = phoneController.text;
String gender = genderController.text;

print("UPDATE" +
dataInputs.id +
name +
birthDate +
phone +
gender);

updateData(dataInputs.id, name, birthDate, phone, gender);

Navigator.of(context).pop();
},
child: const Text(
"Update",
style: TextStyle(fontWeight: FontWeight.bold),
),
),
TextButton(
onPressed: () {
Navigator.of(context).pop();
},
child: const Text(
"Cancel",
style: TextStyle(fontWeight: FontWeight.bold),
),
),
],
);
},
);
}
}

/// Model Class
class UpdateDioModel {
final String id;
final String name;
final String birth_date;
final String phone;
final String gender;

UpdateDioModel({
required this.id,
required this.name,
required this.birth_date,
required this.phone,
required this.gender,
});

factory UpdateDioModel.fromJson(Map<String, dynamic> json) {
return UpdateDioModel(
id: json["id"],
name: json["name"],
birth_date: json["birth_date"],
phone: json["phone"],
gender: json["gender"],
);
}
}

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