Database (Sqflite Database) Creation and Add Data in 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/Widgets/uihelper.dart";
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: "Add Data",
debugShowCheckedModeBanner: false,
theme: ThemeData(
appBarTheme: const AppBarTheme(
backgroundColor: Colors.grey,
centerTitle: true,
),
),
home: const AddData(),
);
}
}
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(
UserModel(title: title, desc: desc),
);
titleController.clear();
descController.clear();
UiHelper.customSnackBar(
text: "Data inserted Successfully...", 2, context);
return log("Data inserted Successfully...");
}
}
}
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 Notetable = "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 $Notetable ($Note_id integer primary key autoincrement,"
" $Note_title text, $Note_desc text)");
},
);
}
Future<bool> addNotes(UserModel newuser) async {
var db = await getDb();
int inserteddata = await db.insert(Notetable, newuser.toMap());
return inserteddata > 0;
}
}import 'package:wslc_sqflite_database_with_modelclass/Database/dbhelper.dart';
class UserModel {
int? id;
String title;
String desc;
UserModel({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 UserModel.fromMap(Map<String, dynamic> mapdata) {
return UserModel(
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,
};
}
}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
Post a Comment