Flutter CRUD Application Tutorial within 3 minutes for flutter developers

Geno Tech
Geno Tech
Jan 22 · 6 min read
Image for post
Image for post

I will explain how to develop a CRUD application using flutter mobile development framework and Sqlite Database. I will describe every signal point you want to know as a flutter developer. This is one of the basic knowledge which any mobile developer getting to know at there beginner level. Also, other flutter expertise can refresh their knowledge in Flutter. Cool !!!

In my flutter developer journey, I will share my experience and knowledge as much as possible. Therefore follow me for more tech articles in Flutter. I recommend every beginner need to know about a few functionalities of mobile apps such as Activities, Fragments, CRUD operations, Firebase integration, how to develop an API and connect to databases etc. This is one of that critical functionality you must know as a Flutter Engineer. The main advantage of here is you can clarify and also you can implement the application to verify your knowledge. Let’s continue with developments.

First, you want to create a new flutter application. Here I used the Android Studio as my IDE, but you can use the VS code or any Flutter development IDE. I will show you every step you need to achieve our goal. Finally, you would implement an application, which has the functionalities with data insert, read, delete and update.

Image for post
Image for post

Then you need to create the grocery item class using item.dart file inside the lib/ folder. because we are going to develop a grocery list creation app.

class Item{
int id;
String name;

Item(this.id, this.name);

Map<String, dynamic> toMap() {
var map = <String, dynamic>{
'id': id,
'name':name,
};

return map;
}

Item.fromMap(Map<String, dynamic> map){
id = map['id'];
name = map['name'];
}
}

Cool !!! It’s easy, few more steps to go.

Next, you need to create the DBHelper class. Before that we adding the dependencies which we want to utilize(sqflite).

dependencies:
flutter:
sdk: flutter

# The following adds the Cupertino Icons font to your application.
# Use with the CupertinoIcons class for iOS style icons.
cupertino_icons: ^0.1.2

sqflite: any
path_provider: any

Then we can create the DBHelper as follows. Create a new file inside the lib/ folder and name it as db_helper.dart. Here you can see all the necessary methods and their functionalities. How to add, delete, update and get data from the database. Also how to create a database and work with it.

import 'dart:async';
import 'dart:io' as io;
import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart';
import 'package:path_provider/path_provider.dart';
import 'item.dart';

class DBHelper {
static Database _db;
static const String ID = 'id';
static const String NAME = 'name';
static const String TABLE = 'Item';
static const String DB_NAME = 'item1.db';

Future<Database> get db async {
if (_db != null) {
return _db;
}
_db = await initDb();
return _db;
}

initDb() async {
io.Directory documentsDirectory = await getApplicationDocumentsDirectory();
String path = join(documentsDirectory.path, DB_NAME);
var db = await openDatabase(path, version: 1, onCreate: _onCreate);
return db;
}

_onCreate(Database db, int version) async {
await db
.execute("CREATE TABLE $TABLE ($ID INTEGER PRIMARY KEY, $NAME TEXT)");
}

Future<Item> save(Item item) async {
var dbClient = await db;
item.id = await dbClient.insert(TABLE, item.toMap());
return item;
}

Future<List<Item>> getItems () async {
var dbClient = await db;
List<Map> maps = await dbClient.query(TABLE, columns: [ID, NAME]);
List<Item> items = [];
if (maps.length > 0) {
for (int i = 0; i < maps.length; i++) {
employees.add(Item.fromMap(maps[i]));
}
}
return items;
}

Future<int> delete(int id) async {
var dbClient = await db;
return await dbClient.delete(TABLE, where: '$ID = ?', whereArgs: [id]);
}

Future<int> update(Item item) async {
var dbClient = await db;
return await dbClient.update(TABLE, item.toMap(),
where: '$ID = ?', whereArgs: [item.id]);
}

Future close() async {
var dbClient = await db;
dbClient.close();
}
}

Finally, you need to implement widgets. There have two widgets mainly. One is a form for add/update data. Second is the Data table with two columns to show the item name and delete the item.

import 'package:flutter/material.dart';
import 'item.dart';
import 'dart:async';
import 'db_helper.dart';
import 'dart:developer';


void main() => runApp(MyApp());

class MyApp extends StatelessWidget{
@override
Widget build(BuildContext context) {
// TODO: implement build
return MaterialApp(
title: "Flutter crud",
theme: ThemeData(
primarySwatch: Colors.blue,

),
home: MyHomePage(),
);
}
}

class MyHomePage extends StatefulWidget {
@override
State<StatefulWidget> createState(){
return _MyHomePageState();
}
}

class _MyHomePageState extends State<MyHomePage> {

Future<List<Item>> items;
TextEditingController controller = TextEditingController();
String name;
int curUserId;

final formKey = new GlobalKey<FormState>();
var dbHelper;
bool isUpdating = false;

@override
void initState() {
super.initState();
dbHelper = DBHelper();
isUpdating = false;
refreshList();
}
// Refresh the list after update the items
refreshList(){
setState(() {
items = dbHelper.getItems();
});
}
// Clear the name when after added or updated item name
clearName(){
controller.text = '';
}
// Data table load items under vertical scroll view
SingleChildScrollView dataTable(List<Item> items){
return SingleChildScrollView(
scrollDirection: Axis.vertical,
child: DataTable(
columns: [
DataColumn(
label: Text('ITEM NAME')
),
DataColumn(
label: Text('DELETE')
)
],
rows: items.map(
(item) => DataRow(
cells:[
DataCell(
Text(item.name),
onTap: (){
setState(() {
isUpdating = true;
curUserId = item.id;
});
controller.text = item.name;
}
),
DataCell(
IconButton(
icon : Icon(Icons.delete),
onPressed: (){
dbHelper.delete(item.id);
refreshList();
},
)
)
]
),
).toList(),
),
);
}
// list widget load here, Inside this, call to create table
list(){
return Expanded(
child: FutureBuilder(
future: items,
builder: (context, snapshot){
log('data1: $snapshot');
if(snapshot.hasData){
return dataTable(snapshot.data);
}
if(null == snapshot.data || snapshot.data.length == 0){
return Text("No Data Found");
}
return CircularProgressIndicator();
},
)
);
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("FLUTTER CRUD"),
),
body: new Container(
child: new Column(
mainAxisAlignment: MainAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
verticalDirection: VerticalDirection.down,
children:<Widget>[
form(),
list(),
],
),
),
);
}
// Create the form with add/update text field and two buttons
form(){
return Form(
key: formKey,
child:Padding(
padding: EdgeInsets.all(10.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
mainAxisSize: MainAxisSize.min,
verticalDirection: VerticalDirection.down,
children: <Widget>[
TextFormField(
controller: controller,
keyboardType: TextInputType.text,
decoration: InputDecoration(labelText: 'Item Name'),
validator: (val) => val.length == 0 ? 'Enter Item Name' : null,
onSaved: (val) => name = val,
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
FlatButton(
onPressed: validate,
child:Text(isUpdating ? 'UPDATE' : 'ADD'),
),
FlatButton(
onPressed: (){
setState(() {
isUpdating = false;
});
clearName();
},
child: Text('CANCEL'),
)
]
)
],
)
)
);
}
// Validate the txt field
validate() {
if(formKey.currentState.validate()){
formKey.currentState.save();
if(isUpdating){
Item e = Item(curUserId, name);

log('data updating');
dbHelper.update(e);
setState(() {
isUpdating = false;
});

}else{
log('data saving');
Item e = Item(null, name);
dbHelper.save(e);
}
clearName();
refreshList();
}
}
}

That’s all !!! Let’s run and see the result application. It’s like follows.

Image for post
Image for post
Image for post
Image for post
Image for post
Image for post

Conclusion

This story gives you the practical knowledge to build a CRUD application
in Flutter with Sqlite. Please feel free to ask any question you will face in
the response section below.
Happy Coding !!!!
Found this post useful? Kindly tap the 👏 button below! :)

App Dev Community

This is for Mobile App Developer to exploring and sharing the knowledge.

Geno Tech

Written by

Geno Tech

Mobile I Web I Data Science I AI — We write rich & meaningful content on development, technology, digital transformation & life lessons.

App Dev Community

A group of mobile app developers sharing the knowledge

Geno Tech

Written by

Geno Tech

Mobile I Web I Data Science I AI — We write rich & meaningful content on development, technology, digital transformation & life lessons.

App Dev Community

A group of mobile app developers sharing the knowledge

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store