Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import 'dart:async';
- import 'package:path/path.dart';
- import 'package:sqflite/sqflite.dart';
- import '../models/dog.dart';
- class DatabaseClient {
- Database _db;
- Future open() async {
- String dbPath = join(await getDatabasesPath(), 'database.db');
- _db = await openDatabase(dbPath, version: 1, onCreate: this._create);
- }
- Future _create(Database db, int version) async {
- await db.execute("""
- CREATE TABLE dogs (
- id INTEGER PRIMARY KEY,
- name TEXT,
- age INTEGER
- )""");
- }
- Future<void> insertDog(Dog dog) async {
- await _db.insert('dogs', dog.toMap(),
- conflictAlgorithm: ConflictAlgorithm.replace);
- }
- Future<Dog> getDog(int id) async {
- final List<Map<String, dynamic>> maps =
- await _db.query('dogs', where: "id = ?", whereArgs: [id], limit: 1);
- if (maps.length > 0) {
- return Dog.fromMap(maps[0]);
- } else {
- return null;
- }
- }
- Future<List<Dog>> getDogs() async {
- final List<Map<String, dynamic>> maps = await _db.query('dogs');
- return List.generate(maps.length, (i) {
- return Dog.fromMap(maps[i]);
- });
- }
- Future<void> updateDog(Dog dog) async {
- _db.update(
- 'dogs',
- dog.toMap(),
- where: "id = ?",
- whereArgs: [dog.id],
- );
- }
- Future<void> deleteDog(int id) async {
- await _db.delete('dogs', where: "id = ?", whereArgs: [id]);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement