Creating a Simple App Using sqflite Flutter

Kiran Bablani
MindOrks
Published in
4 min readMay 22, 2019

Flutter is a new way to build UIs for mobile, but it has a plugin system to communicate with Android and iOS for non-UI tasks.
In this demo project we will be creating simple notes app with sqflite database in Flutter

I hope you guys have some basic understanding of creating apps and widget in Flutter. Let’s learn by creating a new project . Go to your preferred IDE and start a new Flutter project.

A file main.dart is created. If you don’t know about dart file, read here.

First we will add sqflite dependency in our pubspec.yaml file

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
fluttertoast: ^3.0.4
sqflite: ^1.1.0 //sqflite dependency

Step 1.Create main.dart file

import 'package:flutter/material.dart';
void
main() {
runApp(MyApp());
}

class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(
primaryColor: Colors.blue,
),
home: MyHomePage(),
);
}
}

class MyHomePage extends StatelessWidget {
var title = "Notes App";
@override
Widget build(BuildContext context) {
// TODO: implement build
return Scaffold(
appBar: AppBar(
title: Text(title),
),
body: mySampleWidgetWithThreeButtons(),
floatingActionButton: FloatingActionButton(
onPressed: () {
dbFunctions.createNote("Hey!","Hey, Guest\n Welcome to my app");
},
tooltip: 'Create',
child: Icon(Icons.add)));
}

}

Widget mySampleWidgetWithThreeButtons() {
return Center(
// Center is a layout widget. It takes a single child and positions it
// in the center of the parent.
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
FlatButton(
onPressed: () => {dbFunctions.getAllNotes()},
child: Text("Show Notes"),
),
Padding(
padding: const EdgeInsets.all(3),
),
FlatButton(
onPressed: () => {dbFunctions.updateNote(1, "Updated note", "Updated note descriptions")},
child: Text("Update Notes"),
),
Padding(
padding: const EdgeInsets.all(3),
),
FlatButton(
onPressed: () => {dbFunctions.deleteNote(1)},
child: Text("Delete Notes"),
),
],
), // This trailing comma makes auto-formatting nicer for build methods.
);
}

=> StatelessWidgets: Do not change on user interaction, like, Text, Icon.

=> StatefulWidget: Whose state are to be saved .Change on user interactions: for example, checkboxes and radio buttons.

Step 2. Now let’s create notes.dart which is basically our model class.

class Notes {
int _id;
String _title;
String _description;

Notes(this._title, this._description);

Notes.map(dynamic obj) {
this._id = obj['id'];
this._title = obj['title'];
this._description = obj['description'];
}

int get id => _id;
String get title => _title;
String get description => _description;

Map<String, dynamic> toMap() {
var map = new Map<String, dynamic>();
if (_id != null) {
map['id'] = _id;
}
map['title'] = _title;
map['description'] = _description;

return map;
}

Notes.fromMap(Map<String, dynamic> map) {
this._id = map['id'];
this._title = map['title'];
this._description = map['description'];
}
}

Step 3. Creating databasehelper.dart.

import 'dart:async';

import 'package:sqflite/sqflite.dart';
import 'package:path/path.dart';
import 'package:flutter_app/model/Notes.dart';

class DatabaseHelper {
static final DatabaseHelper _instance = DatabaseHelper.internal();

factory DatabaseHelper() => _instance;

final String tableNote = 'noteTable';
final String columnId = 'id';
final String columnTitle = 'title';
final String columnDescription = 'description';

static Database _db;

DatabaseHelper.internal();

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

return _db;
}

initDb() async {
String databasesPath = await getDatabasesPath();
String path = join(databasesPath, 'notes.db');

await deleteDatabase(path); // just for testing

var db = await openDatabase(path, version: 1, onCreate: _onCreate);
return db;
}

void _onCreate(Database db, int newVersion) async {
await db.execute(
'CREATE TABLE $tableNote($columnId INTEGER PRIMARY KEY, $columnTitle TEXT, $columnDescription TEXT)');
}

Future<int> saveNote(Notes note) async {
var dbClient = await db;
var result = await dbClient.insert(tableNote, note.toMap());

return result;
}

Future<List> getAllNotes() async {
var dbClient = await db;
var result = await dbClient.query(tableNote, columns: [columnId, columnTitle, columnDescription]);

return result.toList();
}

Future<int> getCount() async {
var dbClient = await db;
return Sqflite.firstIntValue(await dbClient.rawQuery('SELECT COUNT(*) FROM $tableNote'));
}

Future<Notes> getNote(int id) async {
var dbClient = await db;
List<Map> result = await dbClient.query(tableNote,
columns: [columnId, columnTitle, columnDescription],
where: '$columnId = ?',
whereArgs: [id]);


if (result.length > 0) {
return new Notes.fromMap(result.first);
}

return null;
}

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

}

Future<int> updateNote(Notes note) async {
var dbClient = await db;
return await dbClient.update(tableNote, note.toMap(), where: "$columnId = ?", whereArgs: [note.id]);

}

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

Step 4. Creating dbfunctions.dart.

import 'package:flutter_app/model/Notes.dart';
import 'package:flutter_app/db/databaseHelper.dart';
import 'package:fluttertoast/fluttertoast.dart';
class DbFunctions{

List notes;
var db = DatabaseHelper();

Future createNote(String title,String desc) async {
var note = Notes(title,desc);
await db.saveNote(note);
Fluttertoast.showToast(msg:"Done");
}

Future getAllNotes() async{
notes = await db.getAllNotes();
notes.forEach((note) => print(note));
}

Future updateNote(int id,String title,String desc) async{
Notes updatedNote =
Notes.fromMap({'id': id, 'title': title, 'description': desc});
await db.updateNote(updatedNote);
}

Future deleteNote(int id) async{
await db.deleteNote(id);
notes = await db.getAllNotes();
notes.forEach((note) => print(note));
}

}

We are done with the development now. Run the project and observe logs .

Also checkout project on Github.

Suggestions are always invited!! Happy Coding

--

--