Sqflite Local Database In Flutter

Sqflite Local Database In Flutter :

This flutter tutorial is save the data local database using sqflite BLoC pattern in your mobile. This local database table name is Subject and database name is fluttertutorial.db.

Add dependencies in pubspec.yaml file.
dependencies:
sqflite:
path_provider:

Here local database three field:
1) id : PRIMARY KEY
2) name : TEXT
3) is_done : INTEGER

Task:
1) Insert
subjectBloc.addSubject(newSubject);
2) Get
subjectBloc.getSubject();
3) Update
subjectBloc.updateSubject(subject);
4) Delete
5) Search:
subjectBloc.getSubject(query: searchController.value.text);

Screenshot 1 :

Sqflite Local Database In Flutter

Screenshot 2 :

Sqflite Local Database In Flutter

Screenshot 3 :

Sqflite Local Database In Flutter

Screenshot 4 :

Sqflite Local Database In Flutter

File Structure Screenshot :

Sqflite Local Database In Flutter

Model package

– subject.dart

class Subject {
  int id;
  String name;
  bool isDone = false;

  Subject({this.id, this.name, this.isDone = false});

  factory Subject.fromDatabaseJson(Map<String, dynamic> data) => Subject(
        id: data['id'],
        name: data['name'],
        isDone: data['is_done'] == 0 ? false : true,
      );

  Map<String, dynamic> toDatabaseJson() => {
        "id": this.id,
        "name": this.name,
        "is_done": this.isDone == false ? 0 : 1,
      };
}

Database Package

database.dart

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

final tableName = 'Subject';
class DatabaseProvider {
  static final DatabaseProvider dbProvider = DatabaseProvider();

  Database _database;

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

  createDatabase() async {
    Directory documentsDirectory = await getApplicationDocumentsDirectory();
    String path = join(documentsDirectory.path, "fluttertutorial.db");

    var database = await openDatabase(path,
        version: 1, onCreate: initDB, onUpgrade: onUpgrade);
    return database;
  }

  //This is optional, and only used for changing DB schema migrations
  void onUpgrade(Database database, int oldVersion, int newVersion) {
    if (newVersion > oldVersion) {}
  }

  void initDB(Database database, int version) async {
    await database.execute("CREATE TABLE $tableName ("
        "id INTEGER PRIMARY KEY, "
        "name TEXT, "
        "is_done INTEGER "
        ")");
  }
}

Dao Package

subject_dao.dart

import 'dart:async';

import 'package:local_database/database/database.dart';
import 'package:local_database/model/subject.dart';

class SubjectDao {
  final dbProvider = DatabaseProvider.dbProvider;

  //Adds new
  Future<int> createSubject(Subject subject) async {
    final db = await dbProvider.database;
    var result = db.insert(tableName, subject.toDatabaseJson());
    return result;
  }

  //Get All
  Future<List<Subject>> getSubject({List<String> columns, String query}) async {
    final db = await dbProvider.database;

    List<Map<String, dynamic>> result;
    if (query != null) {
      if (query.isNotEmpty)
        result = await db.query(tableName,
            columns: columns, where: 'name LIKE ?', whereArgs: ["%$query%"]);
    } else {
      result = await db.query(tableName, columns: columns);
    }

    List<Subject> subjects = result.isNotEmpty
        ? result.map((item) => Subject.fromDatabaseJson(item)).toList()
        : [];
    return subjects;
  }

  //Update record
  Future<int> updateSubject(Subject todo) async {
    final db = await dbProvider.database;
    var result = await db.update(tableName, todo.toDatabaseJson(),
        where: "id = ?", whereArgs: [todo.id]);
    return result;
  }

  Future<int> deleteSubject(int id) async {
    final db = await dbProvider.database;
    var result = await db.delete(tableName, where: 'id = ?', whereArgs: [id]);
    return result;
  }

  Future deleteAllSubject() async {
    final db = await dbProvider.database;
    var result = await db.delete(
      tableName,
    );

    return result;
  }
}

Repository Package

subject_repository.dart

import 'package:local_database/dao/subject_dao.dart';
import 'package:local_database/model/subject.dart';

class SubjectRepository {
  final subjectDao = SubjectDao();

  Future getAllSubject({String query}) => subjectDao.getSubject(query: query);

  Future insertSubject(Subject subject) => subjectDao.createSubject(subject);

  Future updateSubject(Subject subject) => subjectDao.updateSubject(subject);

  Future deleteSubjectById(int id) => subjectDao.deleteSubject(id);

  Future deleteAllSubject() => subjectDao.deleteAllSubject();
}

Bloc Package

todo_bloc.dart

import 'dart:async';

import 'package:local_database/model/subject.dart';
import 'package:local_database/repository/subject_repository.dart';

class SubjectBloc {
  final _subjectRepository = SubjectRepository();
  final _subjectController = StreamController<List<Subject>>.broadcast();

  get subjectList => _subjectController.stream;

  SubjectBloc() {
    getSubject();
  }

  getSubject({String query}) async {
    _subjectController.sink.add(await _subjectRepository.getAllSubject(query: query));
  }

  addSubject(Subject subject) async {
    await _subjectRepository.insertSubject(subject);
    getSubject();
  }

  updateSubject(Subject subject) async {
    await _subjectRepository.updateSubject(subject);
    getSubject();
  }

  deleteSubjectById(int id) async {
    _subjectRepository.deleteSubjectById(id);
    getSubject();
  }

  dispose() {
    _subjectController.close();
  }
}

UI Package

home_page.dart

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:local_database/bloc/todo_bloc.dart';
import 'package:local_database/model/subject.dart';

class HomePage extends StatelessWidget {
  HomePage({Key key, this.title}) : super(key: key);

  final SubjectBloc subjectBloc = SubjectBloc();
  final String title;

  final DismissDirection _dismissDirection = DismissDirection.horizontal;
  final nameController = TextEditingController();
  final searchController = TextEditingController();

  /*
   subjectBloc.getSubject(query: searchController.value.text);
  */

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(title: Text('Local Database')),
        body: SafeArea(
            child: Container(
                color: Colors.white,
                padding:
                    const EdgeInsets.only(left: 2.0, right: 2.0, bottom: 2.0),
                child: Container(child: getData()))),
        bottomNavigationBar: BottomAppBar(
            color: Colors.white,
            child: Padding(
                padding: EdgeInsets.only(
                    bottom: MediaQuery.of(context).viewInsets.bottom),
                child: new Container(
                    color: Colors.transparent,
                    child: new Container(
                        height: 80,
                        decoration: new BoxDecoration(
                            color: Colors.white,
                            borderRadius: new BorderRadius.only(
                                topLeft: const Radius.circular(10.0),
                                topRight: const Radius.circular(10.0))),
                        child: Padding(
                            padding: EdgeInsets.all(10),
                            child: Row(children: <Widget>[
                              Expanded(
                                  child: TextFormField(
                                      controller: nameController,
                                      textInputAction: TextInputAction.newline,
                                      maxLines: 1,
                                      style: TextStyle(
                                          fontSize: 21,
                                          fontWeight: FontWeight.w400),
                                      autofocus: true,
                                      decoration: const InputDecoration(
                                          hintText: 'Add your subject',
                                          hintStyle: TextStyle(fontSize: 15),
                                          labelText: 'Subject name',
                                          labelStyle: TextStyle(
                                              fontSize: 15,
                                              color: Colors.blue)),
                                      validator: (String value) {
                                        if (value.isEmpty) {
                                          return 'Empty description!';
                                        }
                                        return value.contains('')
                                            ? 'Do not use the @ char.'
                                            : null;
                                      })),
                              CircleAvatar(
                                  backgroundColor: Colors.blue,
                                  radius: 18,
                                  child: IconButton(
                                      icon: Icon(
                                        Icons.save,
                                        size: 22,
                                        color: Colors.white,
                                      ),
                                      onPressed: () {
                                        final newSubject = Subject(
                                            name: nameController.value.text);
                                        if (newSubject.name.isNotEmpty) {
                                          subjectBloc.addSubject(newSubject);
                                        }
                                      }))
                            ])))))));
  }

  getData() {
    return StreamBuilder(
      stream: subjectBloc.subjectList,
      builder: (BuildContext context, AsyncSnapshot<List<Subject>> snapshot) {
        return getSubjectCardWidget(snapshot);
      },
    );
  }

  getSubjectCardWidget(AsyncSnapshot<List<Subject>> snapshot) {
    if (snapshot.hasData) {
      return snapshot.data.length != 0
          ? ListView.builder(
              itemCount: snapshot.data.length,
              itemBuilder: (context, itemPosition) {
                Subject subject = snapshot.data[itemPosition];
                final Widget dismissibleCard = new Dismissible(
                  background: Container(
                    child: Padding(
                        padding: EdgeInsets.only(left: 10),
                        child: Align(
                            alignment: Alignment.centerLeft,
                            child: Text(
                              "Deleting",
                              style: TextStyle(color: Colors.blue),
                            ))),
                    color: Colors.grey.withOpacity(0.1),
                  ),
                  onDismissed: (direction) {
                    //DELETE DATA
                    subjectBloc.deleteSubjectById(subject.id);
                  },
                  direction: _dismissDirection,
                  key: new ObjectKey(subject),
                  child: Card(
                      shape: RoundedRectangleBorder(
                        side: BorderSide(color: Colors.grey[200], width: 0.5),
                        borderRadius: BorderRadius.circular(5),
                      ),
                      color: Colors.white,
                      child: ListTile(
                          leading: InkWell(
                              onTap: () {
                                subject.isDone = !subject.isDone;
                                subjectBloc.updateSubject(subject);
                              },
                              child: Container(
                                  //decoration: BoxDecoration(),
                                  child: Padding(
                                      padding: const EdgeInsets.all(15.0),
                                      child: subject.isDone
                                          ? Icon(
                                              Icons.check_box,
                                              size: 26.0,
                                              color: Colors.grey,
                                            )
                                          : Icon(
                                              Icons.check_box_outline_blank,
                                              size: 26.0,
                                              color: Colors.grey,
                                            )))),
                          title: Text(
                            subject.name,
                            style: TextStyle(
                                fontSize: 16.5,
                                fontFamily: 'RobotoMono',
                                fontWeight: FontWeight.w500,
                                decoration: subject.isDone
                                    ? TextDecoration.lineThrough
                                    : TextDecoration.none),
                          ))),
                );
                return dismissibleCard;
              })
          : Container(
              child: Center(
              child: noData(),
            ));
    } else {
      return Container();
    }
  }

  noData() {
    return Container(
        child: Text(
      "No data",
      style: TextStyle(fontSize: 19, fontWeight: FontWeight.w500),
    ));
  }

  dispose() {
    subjectBloc.dispose();
  }
}

main.dart

import 'package:flutter/material.dart';

import 'ui/home_page.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Flutter Tutorial',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: HomePage(title: 'Local Database'),
    );
  }
}

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