SQFlite List Json in flutter
{
"result" : [
{
"id" : 1,
"name" : "Avi",
"age" : 22
},
{
"id" : 2,
"name" : "Avi",
"age" : 22
}
],
"status" : 'ok'
}
1. UserModel
// To parse this JSON data, do
//
// final bookModel = bookModelFromJson(jsonString);
import 'dart:convert';
BookModel bookModelFromJson(String str) => BookModel.fromJson(json.decode(str));
String bookModelToJson(BookModel data) => json.encode(data.toJson());
class BookModel {
List<Result> result;
String status;
BookModel({
required this.result,
required this.status,
});
factory BookModel.fromJson(Map<String, dynamic> json) => BookModel(
result: List<Result>.from(json["result"].map((x) => Result.fromJson(x))),
status: json["status"],
);
Map<String, dynamic> toJson() => {
"result": List<dynamic>.from(result.map((x) => x.toJson())),
"status": status,
};
}
class Result {
final int? id;
final String book;
final int price;
Result({
this.id,
required this.book,
required this.price,
});
factory Result.fromJson(Map<String, dynamic> json) => Result(
id: json["id"],
book: json["book"],
price: json["price"],
);
Map<String, dynamic> toJson() => {
"id": id,
"book": book,
"price": price,
};
}
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
)
''');
db.execute('''
CREATE TABLE Bt(
id INTEGER PRIMARY KEY,
book TEXT,
price INTEGER
)
''');
});
return _database!;
}
Future<void> insertBook(Result book) async {
Database? db = await database;
await db!.insert(
"Bt",
book.toJson()
);
}
Future<List<Result>> readBook() async {
final db = await database;
List<Map<String, dynamic>> maps = await db!.query("Bt");
return List.generate(maps.length, (i) {
return
Result(
id: maps[i]['id'],
book: maps[i]['book'],
price: maps[i]['price'],
);
});
}
}
3. Calling (insert & read Method)
ElevatedButton(child: Text("Insert"),
onPressed: ()async{
await DbHandler().insertBook(
Result(
id: 1,
book: nameController.text,
price: 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);
},),
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().readBook(),
builder: (context, AsyncSnapshot<List<Result>> snapshot) {
if(!snapshot.hasData) return CircularProgressIndicator();
return ListView.builder(
itemCount: snapshot.data!.length,
itemBuilder: (context, index) {
nameController.text=snapshot.data![index].book ;
ageController.text=snapshot.data![index].price.toString();
return ListTile(
title: Text(snapshot.data![index].book),
subtitle: Text(snapshot.data![index].price.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