Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import 'dart:async';
- import 'dart:convert';
- import 'package:path/path.dart';
- import '../models/dog.dart';
- import 'package:http/http.dart' as http;
- class ApiClient {
- String _url = "https://5fb5817d36e2fa00166a462d.mockapi.io";
- Future<Dog> insertDog(Dog dog) async {
- final response = await http.post(
- join(_url, 'dogs'),
- headers: <String, String>{
- 'Content-Type': 'application/json; charset=UTF-8',
- },
- body: jsonEncode(<String, dynamic>{
- 'name': dog.name,
- 'age': dog.age,
- }),
- );
- if (response.statusCode == 201) {
- return Dog.fromMap(jsonDecode(response.body));
- }
- else {
- throw Exception('Falha ao salvar dado na API');
- }
- }
- Future<Dog> updateDog(Dog dog) async {
- final response = await http.put(
- join(_url, 'dogs/${dog.id}'),
- headers: <String, String>{
- 'Content-Type': 'application/json; charset=UTF-8',
- },
- body: jsonEncode(<String, dynamic>{
- 'name': dog.name,
- 'age': dog.age,
- }),
- );
- if (response.statusCode == 200) {
- return Dog.fromMap(jsonDecode(response.body));
- }
- else {
- throw Exception('Falha ao atualizar um dado na API!');
- }
- }
- Future<Dog> getDog(String id) async {
- final response = await http.get(
- join(_url, 'dogs/$id'));
- if (response.statusCode == 200) {
- return Dog.fromMap(jsonDecode(response.body));
- }
- else {
- throw Exception('Falha ao carregar dados da API!');
- }
- }
- Future<List<Dog>> getDogs() async {
- final response = await http.get(
- join(_url, 'dogs'));
- List<Dog> listDogs;
- if (response.statusCode == 200) {
- final List dogs = jsonDecode(response.body);
- listDogs = List.generate(dogs.length, (i) {
- return Dog.fromMap(dogs[i]);
- });
- return listDogs;
- }
- else {
- throw Exception('Falha ao carregar dados da API!');
- }
- }
- Future deleteDog(String id) async {
- final response = await http.delete(
- join(_url, 'dogs/$id'),
- headers: <String, String>{
- 'Content-Type': 'application/json; charset=UTF-8',
- },
- );
- if (response.statusCode != 200) {
- throw Exception('Falha ao deletar o registro Dog com id=$id!');
- }
- }
- Future deleteAllDogs() async {
- final List<Dog> dogs = await getDogs();
- for (Dog dog in dogs) {
- final response = await http.delete(
- join(_url, 'dogs/${dog.id}'),
- headers: <String, String>{
- 'Content-Type': 'application/json; charset=UTF-8',
- },
- );
- if (response.statusCode != 200) {
- throw Exception('Falha ao deletar o registro Dog com id=${dog.id}!');
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement