Local Database In Flutter

Local Database In Flutter

This post is store data local using sqflite in flutter.

sqllite crud (create – read – update – delete) operaton:
sqflite using insert, update, delete, read, read using where query get in List, read using where query get single record, delete using where.

Local Database In Flutter

employee.dart

class Employee {
  int id;
  String name;

  Employee(this.id, this.name);

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

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

dbhelper.dart

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 'model/employee.dart';

class DBHelper {
  static Database _database;
  static const String COLUMN_ID = 'id';
  static const String COLUMN_NAME = 'name';

  static const String TABLE = 'Employee';
  static const String DB_NAME = 'employee.db';

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

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

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

  Future<int> insert(Employee employee) async {
    var dbClient = await database;
    var result = await dbClient.insert(TABLE, employee.toMap());
    return result;
  }

  Future<List<Employee>> employeeList() async {
    var dbClient = await database;
    List<Map> list = await dbClient.rawQuery('SELECT * FROM $TABLE');
    List<Employee> employees = new List();
    for (int i = 0; i < list.length; i++) {
      var employee = new Employee(list[i]['id'], list[i]['name']);
      employees.add(employee);
    }
    return employees;
  }

  Future<List<Employee>> employeeIdList(int id) async {
    var dbClient = await database;
    List<Map> list = await dbClient.rawQuery('SELECT * FROM $TABLE WHERE id = $id');
    List<Employee> employees = new List();
    for (int i = 0; i < list.length; i++) {
      var employee = new Employee(list[i]['id'], list[i]['name']);
      employees.add(employee);
    }
    return employees;
  }

  Future<Employee> getEmployee(int id) async {
    var dbClient = await database;
    var results = await dbClient.rawQuery('SELECT * FROM $TABLE WHERE id = $id');
    if (results.length > 0) {
      return new Employee.fromMap(results.first);
    }
    return null;
  }

  Future<int> update(Employee employee) async {
    var dbClient = await database;
    return await dbClient.update(TABLE, employee.toMap(), where: '$COLUMN_ID = ?', whereArgs: [employee.id]);
  }

  Future<bool> updateCheck(Employee employee) async {
    var dbClient = await database;
    int res = await dbClient.update(TABLE, employee.toMap(), where: "id = ?", whereArgs: <int>[employee.id]);
    return res > 0 ? true : false;
  }

  Future<int> deleteUsers(Employee employee) async {
    var dbClient = await database;
    int res = await dbClient.rawDelete('DELETE FROM $TABLE WHERE id = ?', [employee.id]);
    return res;
  }

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

main.dart

import 'package:flutter/material.dart';

import 'dbhelper.dart';
import 'model/employee.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'FLUTTER TUTORIAL',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'FLUTTER SQFLITE'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);
  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  var dbHelper = DBHelper();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(title: Text(widget.title)),
        body: Text(''),
        floatingActionButton: FloatingActionButton(
            onPressed: () {
              var insertData = dbHelper.insert(Employee(1, 'Flutter tutorial'));
              print(insertData);

              dbHelper.employeeList().then((val) {
                print(val.length);
              });

              Future<List<Employee>> empList =  dbHelper.employeeList();
            },
            child: Icon(Icons
                .add)) // This trailing comma makes auto-formatting nicer for build methods.
        );
  }
}

pubspec.yaml

name: local_database
description: A new Flutter application.
version: 1.0.0+1

environment:
  sdk: ">=2.7.0 <3.0.0"

dependencies:
  flutter:
    sdk: flutter

  cupertino_icons:
  sqflite:
  path_provider:

dev_dependencies:
  flutter_test:
    sdk: flutter

flutter:
  uses-material-design: true

The flutter tutorial  is a website that bring you the latest and amazing resources of code. All the languages codes are included in this website. The languages like flutter, android, java,kotlin etc.with the help of this languages any user can develop the beautiful application

For more information about Flutter. visit www.fluttertutorial.in