flutter dart sqlite seed code example

Example 1: flutter sqflite DatabaseHelper

class Todo{
 int id;
 String itemName;
 String dateCreated;

 Todo(
     {this.id,
     this.itemName,
     this.dateCreated})

 //to be used when inserting a row in the table
 Map toMapWithoutId() {
   final map = new Map();
   map["item_name"] = itemName;
   map["date_created"] = dateCreated;
   return map;
 }

Map toMap() {
   final map = new Map();
   map["id"] = id;
   map["item_name"] = itemName;
   map["date_created"] = dateCreated;
   return map;
 }

 //to be used when converting the row into object
 factory Todo.fromMap(Map data) => new Todo(
     id: data['id'],
     itemName: data['item_name'],
     dateCreated: data['date_created']
 );
}

Example 2: flutter sqflite DatabaseHelper

import 'dart:io' as io;

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

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

 factory DatabaseHelper() => _instance;
 static Database _db;

 DatabaseHelper.internal();

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

 Database get db {
   return _db;
 }

 void _onCreate(Database db, int version) async {
   // When creating the db, create the table
   await db.execute(
       'CREATE TABLE todos (id INTEGER PRIMARY KEY AUTOINCREMENT,'
'item_name TEXT,'
           'date_created TEXT')';
 }
}

Tags:

Misc Example