import 'dart:async'; import 'package:path/path.dart'; import 'package:sqflite/sqflite.dart'; import '../models/dog.dart'; class DatabaseClient { Database _db; Future open() async { try { String dbPath = join(await getDatabasesPath(), 'database.db'); _db = await openDatabase(dbPath, version: 1, onCreate: this._create); } catch (error) { throw Exception('Falha ao abrir o BD!'); } } Future _create(Database db, int version) async { try { await db.execute(""" CREATE TABLE dogs ( id TEXT PRIMARY KEY, name TEXT, age INTEGER )"""); } catch (error) { throw Exception('Falha ao criar tabela no BD!'); } } Future insertDogs(List dogs) async { try { await Future.forEach(dogs, (dog) async { await _db.insert('dogs', dog.toMap(), conflictAlgorithm: ConflictAlgorithm.replace); }); } catch (error) { throw Exception('Falha ao inserir lista de dados no BD!'); } } Future insertDog(Dog dog) async { try { await _db.insert('dogs', dog.toMap(), conflictAlgorithm: ConflictAlgorithm.replace); } catch (error) { throw Exception('Falha ao inserir dado no BD!'); } } Future getDog(String id) async { try { final List> maps = await _db.query('dogs', where: "id = ?", whereArgs: [id], limit: 1); if (maps.length > 0) { return Dog.fromMap(maps[0]); } else { return null; } } catch (error) { throw Exception('Falha ao obter dado no BD!'); } } Future> getDogs() async { try { final List> maps = await _db.query('dogs'); return List.generate(maps.length, (i) { return Dog.fromMap(maps[i]); }); } catch (error) { throw Exception('Falha ao obter lista de dados no BD!'); } } Future updateDog(Dog dog) async { try { _db.update( 'dogs', dog.toMap(), where: "id = ?", whereArgs: [dog.id], ); } catch (error) { throw Exception('Falha ao atualizar dado no BD!'); } } Future deleteDog(String id) async { try { await _db.delete('dogs', where: "id = ?", whereArgs: [id]); } catch (error) { throw Exception('Falha ao deletar dado no BD!'); } } Future deleteAllDogs() async { try { await _db.execute("""DELETE FROM dogs"""); } catch (error) { throw Exception('Falha ao deletar todos os dados do BD!'); } } }