Flutter Database SQFlite Create Table and save data into table

Shriya
4 min readSep 10, 2020

Simple way to create database for your flutter app and test it online.

  1. First of all add libraries and create a class to perform all database queries.
  2. Create an instance of database object where you want to perform action.
  3. Call the defined functions from database to your widget file.

1.)Add Library

sqflite: ^1.2.0
path_provider: ^1.5.1

2.)DBHelper.dart

class DBHelper {
static Database _database;
static const String TABLE_CUSTOMER = "Customer";
static const String TABLE_PRODUCT = "Product";

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

initDatabase() async {
io.Directory docdir = await getApplicationDocumentsDirectory();
String path = join(docdir.path, 'app.db');
print('=====Database path==== ' + path);
var db = await openDatabase(path, version: 1, onCreate: _onCreate);
return db;
}

Future _onCreate(Database db, int version) async {
await db.execute('CREATE TABLE $TABLE_CUSTOMER '
'(id INTEGER PRIMARY KEY '
'AUTOINCREMENT,'
' name TEXT,'
' email TEXT,'
' phone TEXT,'
' city TEXT'
')'
);

await db.execute('CREATE TABLE $TABLE_PRODUCT '
'(id INTEGER PRIMARY KEY,'
' name TEXT'
')'
);
}


Future<Customer> addCustomer(Customer customer)
async {
var dbClient = await db;
customer.id = await dbClient.insert(TABLE_CUSTOMER,
customer.toJson());
print('customer ' + customer.name);
return customer;
}

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

3.)main.dart

Initialize database instance in main.dart

DBHelper db = new DBHelper();
await db.initDatabase();

runApp(
MyApp(),
);

4.) Customer.dart

class Customer {
int id;
String name;
String phone;
String city;
String email;

Customer(
{this.id,
this.name,
this.phone,
this.city,
this.email});

factory Customer.fromJson(Map<String, dynamic> parsedJson) {
return Customer(
id: parsedJson['id'],
name: parsedJson['name'],
phone: parsedJson['phone'],
city: parsedJson['city'],
email: parsedJson['email']);
}

Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['name'] = this.name;
data['phone'] = this.phone;
data['city'] = this.city;
data['email'] = this.email;
return data;
}
}

5.) MyPage.dart

class MyPage extends StatefulWidget {
@override
_MyPageState createState() => _MyPageState();
}

class _MyPageState extends State<MyPage> {
DBHelperHome dbHelper = new DBHelperHome();

final GlobalKey<ScaffoldState> _scaffoldKey =
new GlobalKey<ScaffoldState>();
TextEditingController _nameCtrler = new TextEditingController();
TextEditingController _emailCtrler = new TextEditingController();
TextEditingController _phoneCtrler = new TextEditingController();
TextEditingController _cityCtrler = new TextEditingController();

String _name, _mobile, _email, _city, _phone;

@override
void initState() {
super.initState();
}

@override
Widget build(BuildContext context) {
return new WillPopScope(
child: Scaffold(
key: _scaffoldKey,
appBar: AppBar(
centerTitle: true,
backgroundColor: Colors.yellow,
title: Text(
"Database Tutorial",
style: TextStyle(color: Colors.black),
),
leading: Container(),
),
resizeToAvoidBottomPadding: false,
body: SingleChildScrollView(
child: Container(
color: Colors.white,
padding: EdgeInsets.all(20),
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Container(
margin: EdgeInsets.only(left: 10,
right: 10),
child: Column(
children: [
SizedBox(
height: 100,
),
TextField(
decoration: InputDecoration(
border: OutlineInputBorder(),
labelText: 'Name',
),
controller: _nameCtrler,
),
SizedBox(
height: 10,
),
TextField(
decoration: InputDecoration(
border: OutlineInputBorder(),
labelText: 'Email',
),
controller: _emailCtrler,
),
SizedBox(
height: 10,
),
TextField(
decoration: InputDecoration(
border: OutlineInputBorder(),
labelText: 'Phone',
),
controller: _phoneCtrler,
),
SizedBox(
height: 10,
),
TextField(
decoration: InputDecoration(
border: OutlineInputBorder(),
labelText: 'City',
),
controller: _cityCtrler,
),
SizedBox(
height: 20,
),
InkWell(
child: Container(
alignment: Alignment.center,
margin: EdgeInsets.only(
bottom: 10, left: 20,
right: 20),
height: 35,
width: MediaQuery.of(context)
.size.width,
decoration: new BoxDecoration(
borderRadius: BorderRadius.
circular(5.0),
color: Colors.yellow,
),
child: Text(
"Add",
style: TextStyle(color:
Colors.black, fontSize: 18),
),
),
onTap: () {
saveData();
},
),
],
),
)
],
),
),
)));
}

bool isValid() {
_name = _nameCtrler.text;
_mobile = _phoneCtrler.text;
_city = _cityCtrler.text;
_email = _emailCtrler.text;
_phone = _phoneCtrler.text;

if (!(_name.length > 0)) {
showSnackBar("Please enter name");
return false;
} else if (!(_email.length > 0)) {
showSnackBar("Please enter email");
return false;
} else if (!(_mobile.length > 0)) {
showSnackBar("Please enter mobile");
return false;
} else {
return true;
}
}

void saveData() {
if (isValid()) {
Customer customer = new Customer(
name: _name,
email: _email,
phone: _phone,
city: _city,
);

Future<Customer> future = dbHelper.addCustomer(customer);
future.then((_cus) {
if (_cus != null) {
print('result added-' + _cus.name);
}
});
}
}

showSnackBar(String value) {
_scaffoldKey.currentState
.showSnackBar(new SnackBar(content: new Text(value)));
}
}
Image to refer the code.

Now, follow steps to check your database:

  1. Open window ‘Device File Explorer’ in android studio.
  2. Follow your path data/data/app_flutter/app.db (in your case it might be different)
  3. Right click on app.db file and save as on desktop.
  4. Open link in browser https://sqliteonline.com/
  5. Go to file>Open DB
  6. Here choose app.db and your database is visible here just like below image. You can fire any query and test your database possibilities.

If you have any query then you can write it in comments.
I am ready to help you :)

--

--