Wednesday 26 May 2021

Flutter Add & Edit Page To Insert & Update Data Inside SQFLITE Database Table






NOTE : You can download a whole project from  https://unpossiblepog.com/projects/dart+flutter+sqflite/Flutter-Basic-SQFLITE-Database-Project-Create-Insert-Update-Delete


1. In main.dart file, need to add new column called action, which will contain an EDIT button for each entry. For that, replace the “getDynamicTable” function with following code.


Table getDynamicTable() {

List<TableRow> rows = [];

rows.add(TableRow(children: [

Text("Id"),

Text("Name "),

Text("Address "),

Text("Actions"),

]));

if(employeeFinalList!=null)

{

for (int i = 0; i < this.employeeFinalList.length; ++i) {

rows.add(TableRow(children: [

Text(""+employeeFinalList[i]['id'].toString()),

Text("" + employeeFinalList[i]['name'].toString()),

Text("" + employeeFinalList[i]['address'].toString()),

new RaisedButton(

child: new Text('EDIT'),

onPressed: () {

Navigator.push(

context,

MaterialPageRoute(builder: (context) => insertPage(id:int.parse(employeeFinalList[i]['id']))),

);

},

)

]));

}

}

return Table(

border:TableBorder.all(width: 2.0,color: Colors.black),

columnWidths: {

0: FixedColumnWidth(100.0),

0: FixedColumnWidth(100.0),

1: FlexColumnWidth(),

},

children: rows,

);

}

-------------------------------

2. Create a new dart file at the place where the main.dart file is present. Give it a name as “addEditPage.dart” and paste the following code inside it.


import 'package:flutter/material.dart';

import 'dart:async';

import 'package:<your_project_folder_name>/database_connector.dart';

import 'package:sqflite/sqflite.dart';

import 'main.dart';

class insertPage extends StatelessWidget {

int id;

String name;

String address;

int fetchData=0;

// This widget is the root of your application.

insertPage({this.id});

var txt_1 = TextEditingController();

var txt_2 = TextEditingController();

@override

Widget build(BuildContext context) {

//print(""+id.toString());

if(id!=0)

{

DBConDisplaySpecificId(id);

}

TextStyle textStyle = Theme.of(context).textTheme.title;

return Scaffold(

appBar: AppBar(

title: Text("Second Route"),

),

body: Padding(

padding: EdgeInsets.only(top: 15.0, left: 10.0, right: 10.0),

child: ListView(

children: <Widget>[

Padding(

padding: EdgeInsets.only(top: 15.0, bottom: 15.0),

child: TextField(

controller: txt_1,

style: textStyle,

onChanged: (value) {

debugPrint('Something changed in Name Text Field');

},

decoration: InputDecoration(

labelText: 'Name',

labelStyle: textStyle,

border: OutlineInputBorder(

borderRadius: BorderRadius.circular(5.0)

)

),

),

),

Padding(

padding: EdgeInsets.only(top: 15.0, bottom: 15.0),

child: TextField(

controller: txt_2,

style: textStyle,

onChanged: (value) {

debugPrint('Something changed in Address Text Field');

},

decoration: InputDecoration(

labelText: 'Address',

labelStyle: textStyle,

border: OutlineInputBorder(

borderRadius: BorderRadius.circular(5.0)

)

),

),

),

Padding(

padding: EdgeInsets.only(top: 15.0, bottom: 15.0),

child: Row(

children: <Widget>[

Expanded(

child: RaisedButton(

color: Theme.of(context).primaryColorDark,

textColor: Theme.of(context).primaryColorLight,

child: Text(

'Save',

textScaleFactor: 1.5,

),

onPressed: () {

debugPrint("Save button clicked");

getValuesFromTextbox();

Navigator.push(

context,

MaterialPageRoute(builder: (context) => MyApp()),

);

},

),

),

Container(width: 5.0,),

],

),

)

]

)

),

);

}

void getValuesFromTextbox()

{

DatabaseConnect con = DatabaseConnect();

final Future<int> dbFuture = con.insertUpdateDynamic(id,txt_1.text,txt_2.text);

}

void DBConDisplaySpecificId(id){

DatabaseConnect con = DatabaseConnect();

List<Map<String, dynamic>> list=[];

final Future<Database> dbFuture = con.initializeDatabase();

dbFuture.then((database) {

Future<List<Map<String, dynamic>>> noteListFuture = con.getSpecificEmployee(id);

noteListFuture.then((emp_data) {

for(var i=0;i<emp_data.length;i++)

{

Map m=emp_data[i];

m.forEach((k,v) =>

{

//print('${k}: ${v}'),

if('${k}'=="name")

{

txt_1.text='${v}',

},

if('${k}'=="address")

{

txt_2.text='${v}',

}

}

);

}

print(emp_data);

});

});

}

}

-------------------------------

3. Then import that file by pasting the following code in “main.dart” file.


import 'addEditPage.dart';

-------------------------------

4. In floating button, onPressed event, add the following code.


() {

Navigator.push(

context,

MaterialPageRoute(builder: (context) => insertPage(id: id)),

);

},

-------------------------------

5. Add new integer variable in the first line of "Widget build" function.


int id=0;

-------------------------------

6. In database_connector.dart file, add the following code inside “DatabaseConnect” class.


Future<int> insertUpdateDynamic(int id,String name,String address) async {

Database db = await this.database;

var result=0;

if(id==0)

{

result = await db.rawInsert("INSERT INTO employee(name,address) VALUES('"+name+"','"+address+"')");

}

else

{

await db.rawUpdate("UPDATE employee set name='"+name+"', address='"+address+"' where id='"+id.toString()+"'");

result=id;

}

return result;

}

Future<List<Map<String, dynamic>>> getSpecificEmployee(int id) async {

    Database db = await this.database;

    var result = await db.rawQuery('SELECT * FROM employee where id='+id.toString()+' order by id ASC');

    return result;

}

-------------------------------
END
-------------------------------

Subscribe my Channel:- http://www.youtube.com/user/SanketRooney?sub_confirmation=1

Facebook Page:- https://www.facebook.com/UnpossibleNS

Twitter Account:- https://twitter.com/UnpossiblePOG

Blog :- https://unpossiblepog.blogspot.in/

-------------------------------

In last part, we displayed database in table format. In this video, we are going create add & edit page from where we can insert or update data.

We already have table structure ready, we shall add new column for edit button.

And we already have add button floating at the bottom of simulator screen.

I created a blog which contains code and instructions.

We just have to copy-paste it.

From 1st point, copy the code and replace the getDynamicTable function.

It will help to add new EDIT column.

For 2nd point, create a new dart file in LIB folder.

Paste the whole code in it.

Make sure to add correct project name, in my case it is “steps”

3rd point says that you have to import newly created file.

From 4th point, onpressed function of floating button, add the given code.

In 5th point, create a new int variable called ID with default value as 0.

From last point, copy the code, go to database_connector.dart file and paste the code inside the class.

Now let’s run the project.

Peter Parker came twice, so I am going to edit the entry.

Let’s add new entry by clicking on floating button.

So that is it, thanks for watching. Like share and subscribe.



No comments:

Post a Comment