1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104
| import 'dart:io'; import 'package:path/path.dart'; import 'package:path_provider/path_provider.dart'; import 'package:sqflite/sqflite.dart';
/// `todo` table name final String tableTodo = 'todo';
/// id column name final String columnId = '_id';
/// title column name final String columnTitle = 'title';
/// done column name final String columnDone = 'done';
/// Todo model. class Todo { /// Todo model. Todo(); /// Read from a record. Todo.fromMap(Map map) { id = map[columnId] as int?; title = map[columnTitle] as String?; done = map[columnDone] == 1; }
/// id. int? id;
/// title. String? title;
/// done. bool? done;
/// Convert to a record. Map<String, Object?> toMap() { var map = <String, Object?>{ columnTitle: title, columnDone: done == true ? 1 : 0 }; if (id != null) { map[columnId] = id; } return map; } @override String toString() { return "id=$id,title=$title,done=$done"; } }
/// Todo provider. class TodoProvider { /// The database when opened. late Database db;
/// Open the database. Future open(String path) async { db = await openDatabase(path, version: 1, onCreate: (Database db, int version) async { await db.execute(''' create table $tableTodo ( $columnId integer primary key autoincrement, $columnTitle text not null, $columnDone integer not null) '''); }); }
/// Insert a todo. Future<Todo> insert(Todo todo) async { todo.id = await db.insert(tableTodo, todo.toMap()); return todo; }
/// Get a todo. Future<Todo?> getTodo(int id) async { List<Map> maps = await db.query(tableTodo, columns: [columnId, columnDone, columnTitle], where: '$columnId = ?', whereArgs: [id]); if (maps.isNotEmpty) { return Todo.fromMap(maps.first); } return null; }
/// Delete a todo. Future<int> delete(int id) async { return await db.delete(tableTodo, where: '$columnId = ?', whereArgs: [id]); }
/// Update a todo. Future<int> update(Todo todo) async { return await db.update(tableTodo, todo.toMap(), where: '$columnId = ?', whereArgs: [todo.id!]); }
/// Close database. Future close() async => db.close(); }
|