Database (Sqflite Database) data inserted and fetch data from Database with Model Class

 import "dart:developer";

import "package:flutter/material.dart";
import "package:wslc_sqflite_database_with_modelclass/Database/dbhelper.dart";
import "package:wslc_sqflite_database_with_modelclass/Model/dbmodel.dart";
import "package:wslc_sqflite_database_with_modelclass/Screens/addData.dart";

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

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

@override
Widget build(BuildContext context) {
return MaterialApp(
title: "Notes App",
debugShowCheckedModeBanner: false,
theme: ThemeData(
appBarTheme: const AppBarTheme(
backgroundColor: Colors.grey,
centerTitle: true,
),
),
home: const NotesApp(),
);
}
}

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

@override
State<NotesApp> createState() {
return NotesAppState();
}
}

class NotesAppState extends State<NotesApp> {
late DbHelper mydb;
List<NotesModel> arrNotes = [];

@override
void initState() {
super.initState();
mydb = DbHelper.dbHelper;
getNotes();
}

getNotes() async {
arrNotes = await mydb.fetchData();
setState(() {});
log(arrNotes[0].title);
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text(
"Notes App",
style: TextStyle(fontWeight: FontWeight.bold),
),
),
floatingActionButton: FloatingActionButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) {
return AddData();
},
),
);
},
backgroundColor: Colors.blue,
child: const Icon(Icons.add, color: Colors.white, size: 30.0),
),
body: ListView.builder(
itemCount: arrNotes.length,
itemBuilder: (context, index) {
return Card(
child: ListTile(
leading: Text(
"${index + 1}",
style: const TextStyle(
fontWeight: FontWeight.bold, fontSize: 20.0),
),
title: Text(
arrNotes[index].title,
style: const TextStyle(fontWeight: FontWeight.bold),
),
subtitle: Text(arrNotes[index].desc),
),
);
},
),
);
}
}
import 'dart:io';
import "package:path/path.dart";
import 'package:path_provider/path_provider.dart';
import 'package:sqflite/sqflite.dart';
import 'package:wslc_sqflite_database_with_modelclass/Model/dbmodel.dart';

class DbHelper {
static final DbHelper dbHelper = DbHelper();
Database? database;
static const Note_table = "notes";
static const Note_id = "noteid";
static const Note_title = "notetitle";
static const Note_desc = "notedesc";

Future<Database> getDb() async {
if (database != null) {
return database!;
} else {
return await initDb();
}
}

Future<Database> initDb() async {
Directory directory = await getApplicationDocumentsDirectory();
var dbpath = join(directory.path + "notesdb2.db");
return openDatabase(
dbpath,
version: 1,
onCreate: (db, version) {
return db.execute(
"create table $Note_table ($Note_id integer primary key autoincrement,"
" $Note_title text, $Note_desc text)");
},
);
}

Future<bool> addNotes(NotesModel newuser) async {
var db = await getDb();
int inserteddata = await db.insert(Note_table, newuser.toMap());
return inserteddata > 0;
}

Future<List<NotesModel>> fetchData() async {
var db = await getDb();
List<Map<String, dynamic>> notes = await db.query(Note_table);
List<NotesModel> listNotes = [];

for (Map<String, dynamic> notesmodel in notes) {
NotesModel newnote = NotesModel.fromMap(notesmodel);
listNotes.add(newnote);
}
return listNotes;
}
}

import 'package:wslc_sqflite_database_with_modelclass/Database/dbhelper.dart';

class NotesModel {
int? id;
String title;
String desc;

NotesModel({this.id, required this.title, required this.desc});

/// When data will go(data will Add) in database at that time, we will use toMap() function(toMap -> insert)
/// When data will fetch from database at that time, we will use fromMap() function(fromMap -> fetch)
/// When we work with API, at that time, we will use toJson() and fromJson() method

/// Use of "factory" keyword : When data will go in database and when data will fetch from database,
/// at that time small amount of data will be stored in "factory" keyword.

/// To get data(fetch data) from database, fromMap() method is used as shown below:
factory NotesModel.fromMap(Map<String, dynamic> mapdata) {
return NotesModel(
id: mapdata[DbHelper.Note_id],
title: mapdata[DbHelper.Note_title],
desc: mapdata[DbHelper.Note_desc]);
}

/// To Add data(store data) in database, toMap() method is used as shown below:
Map<String, dynamic> toMap() {
return {
DbHelper.Note_id: id,
DbHelper.Note_title: title,
DbHelper.Note_desc: desc,
};
}
}

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

@override
State<AddData> createState() {
return AddDataState();
}
}

class AddDataState extends State<AddData> {
TextEditingController titleController = TextEditingController();
TextEditingController descController = TextEditingController();

@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: () {
return FocusManager.instance.primaryFocus?.unfocus();
},
child: Scaffold(
appBar: AppBar(
title: const Text(
"Add Data",
style: TextStyle(fontWeight: FontWeight.bold),
),
centerTitle: true,
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
UiHelper.customTextFormField(
titleController, "Enter title", Icons.title),
UiHelper.customTextFormField(
descController, "Enter description", Icons.description),
const SizedBox(height: 20.0),
ElevatedButton(
onPressed: () {
addData(titleController.text.toString(),
descController.text.toString());
},
style: ElevatedButton.styleFrom(
backgroundColor: Colors.blue,
fixedSize: const Size(300.0, 50.0),
),
child: const Text(
"Add data",
style: TextStyle(
fontWeight: FontWeight.bold,
color: Colors.white,
fontSize: 20.0),
),
),
],
),
),
),
);
}

addData(String title, String desc) {
if (title == "" && desc == "") {
UiHelper.customSnackBar(text: "Enter required fields", 2, context);
return log("Enter required fields");
} else {
DbHelper().addNotes(
NotesModel(title: title, desc: desc),
);
titleController.clear();
descController.clear();
UiHelper.customSnackBar(
text: "Data inserted Successfully...", 2, context);
return log("Data inserted Successfully...");
}
}
}


import "package:flutter/material.dart";

class UiHelper {
static customTextFormField(
TextEditingController controller, String text, IconData iconData) {
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 25.0, vertical: 15.0),
child: TextFormField(
controller: controller,
decoration: InputDecoration(
hintText: text,
suffixIcon: Icon(iconData),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(11.0),
),
),
),
);
}

static customSnackBar(int seconds, BuildContext context,
{required String text}) {
return ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(text),
duration: Duration(seconds: seconds),
),
);
}
}





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