joaopaulofcc

Untitled

Nov 11th, 2020
537
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import 'dart:async';
  2. import 'package:path/path.dart';
  3. import 'package:sqflite/sqflite.dart';
  4. import '../models/dog.dart';
  5.  
  6. class DatabaseClient {
  7.   Database _db;
  8.  
  9.   Future open() async {
  10.     String dbPath = join(await getDatabasesPath(), 'database.db');
  11.     _db = await openDatabase(dbPath, version: 1, onCreate: this._create);
  12.   }
  13.  
  14.   Future _create(Database db, int version) async {
  15.     await db.execute("""
  16.            CREATE TABLE dogs (
  17.              id INTEGER PRIMARY KEY,
  18.              name TEXT,
  19.              age INTEGER
  20.            )""");
  21.   }
  22.  
  23.   Future<void> insertDog(Dog dog) async {
  24.     await _db.insert('dogs', dog.toMap(),
  25.         conflictAlgorithm: ConflictAlgorithm.replace);
  26.   }
  27.  
  28.   Future<Dog> getDog(int id) async {
  29.     final List<Map<String, dynamic>> maps =
  30.         await _db.query('dogs', where: "id = ?", whereArgs: [id], limit: 1);
  31.  
  32.     if (maps.length > 0) {
  33.       return Dog.fromMap(maps[0]);
  34.     } else {
  35.       return null;
  36.     }
  37.   }
  38.  
  39.   Future<List<Dog>> getDogs() async {
  40.     final List<Map<String, dynamic>> maps = await _db.query('dogs');
  41.  
  42.     return List.generate(maps.length, (i) {
  43.       return Dog.fromMap(maps[i]);
  44.     });
  45.   }
  46.  
  47.   Future<void> updateDog(Dog dog) async {
  48.     _db.update(
  49.       'dogs',
  50.       dog.toMap(),
  51.       where: "id = ?",
  52.       whereArgs: [dog.id],
  53.     );
  54.   }
  55.  
  56.   Future<void> deleteDog(int id) async {
  57.     await _db.delete('dogs', where: "id = ?", whereArgs: [id]);
  58.   }
  59. }
RAW Paste Data