SQFlite Single Json in flutter
{
"id" : 1,
"name" : "Avi",
"age" : 22
}
1. UserModel
class UserModel{
// final int id;
final int id;
final String name;
final int age;
// constructor
UserModel({
// required this.id,
required this.id,
required this.name,
required this.age
});
factory UserModel.fromMap(Map<String,dynamic>map){
return UserModel(
id: map['id'],
name: map['name'],
age: map['age']
);
}
Map<String, dynamic> toJson(){
return {
"id" : id,
"name" : name,
"age" : age
};
}
}
2. Dbhandler
import 'dart:convert';
import 'dart:io';
import 'package:healthtick/model/user_model.dart';
import 'package:healthtick/model/vendor_dj_model.dart';
import 'package:path_provider/path_provider.dart';
import 'package:sqflite/sqflite.dart';
import 'package:path/path.dart';
import 'package:healthtick/model/book_model.dart';
class DbHandler {
Database? _database;
Future<Database?> get database async {
if (_database != null) {
return _database;
}
// Create Database file in your mobile
Directory directory = await getApplicationDocumentsDirectory();
String path = join(directory.path, "mydatabase.db");
// open & create table in database file
_database = await openDatabase(path, version: 1, onCreate: (db, version) {
db.execute('''
CREATE TABLE DatabaseTable(
id INTEGER PRIMARY KEY,
name TEXT,
age INTEGER
)
''');
});
return _database!;
}
// Insert Data with help User Model Class
insertData(UserModel userModel) async {
Database? db = await database;
await db!.insert('DatabaseTable', userModel.toJson());
}
// Fetch/ Read Data in Database Table
Future<List<UserModel>>readData() async {
Database? db = await database;
final data = await db!.query("DatabaseTable");
// return data;
// With model
return data.map((map) => UserModel.fromMap(map)).toList();
}
// Delete Data in Database Table
deleteData(int id)async{
Database? db=await database;
await db!.delete('DatabaseTable' , where: 'id=?',whereArgs: [id]);
}
// Update Data in Database Table
updateData(UserModel userModel) async {
Database? db = await database;
await db!.update(
'DatabaseTable',
where: 'id=?',
whereArgs: [userModel.id],
userModel.toJson());
}
}
3. Calling (insert & read Method)
ElevatedButton(child: Text("Insert"),
onPressed: ()async{
// await DbHandler().insertData(3, "Shesha", 22);
// await DbHandler().insertData(
// UserModel(
id: 5,
name: "Radhe",
age: 23
// name: nameController.text,
// age: int.parse(ageController.text),
);
print("Inserted");
print(nameController.text + ageController.text);
},),
ElevatedButton(child: Text("Read/Fetch"),
onPressed: ()async{
// final data=await DbHandler().readData();
final data=await DbHandler().readBook();
print("Fetch");
print(data);
},),
ElevatedButton(child: Text("Delete"),
onPressed: ()async{
final data=await DbHandler().deleteData(4);
print("Delete");
},),
// ElevatedButton(child: Text("Update"),
// onPressed: ()async{
// final data=await DbHandler().updateData(
// // {
// // 'id' : 3,
// // 'name' : "Anuradha",
// // 'age': 46
// // }
// UserModel(
// name: nameController.text,
// age: int.parse(ageController.text),
// )
// );
// print("Updated");
// },),
4. Fetch Data
import 'package:flutter/material.dart';
import 'package:healthtick/Sqflite/db_handler.dart';
import 'package:healthtick/model/user_model.dart';
import 'model/book_model.dart';
class UserScreen extends StatefulWidget {
const UserScreen({super.key});
@override
State<UserScreen> createState() => _UserScreenState();
}
class _UserScreenState extends State<UserScreen> {
TextEditingController nameController= TextEditingController();
TextEditingController ageController= TextEditingController();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("User Screen"),
backgroundColor: Colors.yellow,
),
body: SafeArea(
child: FutureBuilder(
future: DbHandler().readData(),
builder: (context, AsyncSnapshot<List<UserModel>> snapshot) {
if(!snapshot.hasData) return CircularProgressIndicator();
return ListView.builder(
itemCount: snapshot.data!.length,
itemBuilder: (context, index) {
nameController.text=snapshot.data![index].name ;
ageController.text=snapshot.data![index].age.toString();
return ListTile(
title: Text(snapshot.data![index].name),
subtitle: Text(snapshot.data![index].age.toString()),
trailing: SizedBox(
width: 200,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
ElevatedButton(
child: Text("Update"),
onPressed: ()async{
int id=int.parse(snapshot.data![index].id.toString());
print(id);
showDialog(
context: context,
builder: (context) => AlertDialog(
title: Text("Update Dialog"),
content: Column(
children: [
TextField(
controller: nameController,
decoration: InputDecoration(
filled: true,
fillColor: Colors.white,
hintText: "Enter your name",
labelText: "Name"
),
),
SizedBox(height: 5,),
TextField(
controller: ageController,
keyboardType: TextInputType.number,
decoration: InputDecoration(
filled: true,
fillColor: Colors.white,
hintText: "Enter your age",
labelText: "Age"
),
),
],
),
actions: <Widget>[
TextButton(
onPressed: ()async{
int id=int.parse(snapshot.data![index].id.toString());
print(id);
await DbHandler().updateData(UserModel(
id: id,
name: nameController.text,
age: int.parse(ageController.text),
));
// Navigator.pop(context);
Navigator.pushReplacement(context, MaterialPageRoute(builder: (context)=>UserScreen()));
},
child: Text("Submit"))
],
),
);
// await DbHandler().updateData(
// UserModel(
// name: nameController.text,
// age: int.parse(ageController.text),
// )
// );
print("Update");
},
),
ElevatedButton(
child: Text("Delete"),
onPressed: ()async{
int id=int.parse(snapshot.data![index].id.toString());
print(id);
await DbHandler().deleteData(id);
print("Deleted");
await Navigator.push(context, MaterialPageRoute(builder: (context) => UserScreen()));
},
),
],
),
),
);
},
);
},
),
),
);
}
}
No comments:
Post a Comment