· 5 years ago · Nov 18, 2020, 08:58 PM
1import 'dart:async';
2import 'dart:convert';
3import 'package:flutter/material.dart';
4import 'package:http/http.dart' as http;
5
6class Dog {
7 final String id;
8 final String name;
9 final int age;
10
11 Dog({this.id, this.name, this.age});
12
13 // Método que cria um objeto Dog a partir de um JSON recebido.
14 factory Dog.fromJson(Map<String, dynamic> json) {
15 return Dog(
16 id: json['id'],
17 name: json['name'],
18 age: json['age'],
19 );
20 }
21}
22
23// Método que realiza a leitura de um Dog da API.
24Future<Dog> fetchDog() async {
25 //Insira aqui a URL do endpoint da API.
26 final response =
27 await http.get('https://5fb5817d36e2fa00166a462d.mockapi.io/dogs/1');
28
29 if (response.statusCode == 200) {
30 // Se o servidor retornou uma resposta 200 OK
31 // converte a resposta (JSON) para um objeto da classe Dog.
32 return Dog.fromJson(jsonDecode(response.body));
33 }
34 // Caso o servidor tenha retornado erro lança uma exceção.
35 else {
36 throw Exception('Falha ao carregar dados da API!');
37 }
38}
39
40// Método responsável por deletar um dado na API.
41Future<void> deleteDog(String id) async {
42 final http.Response response = await http.delete(
43 'https://5fb5817d36e2fa00166a462d.mockapi.io/dogs/$id',
44 headers: <String, String>{
45 'Content-Type': 'application/json; charset=UTF-8',
46 },
47 );
48
49 if (response.statusCode != 200) {
50 throw Exception('Failed ao deletar dado!');
51 }
52}
53
54void main() => runApp(MyApp());
55
56class MyApp extends StatefulWidget {
57 MyApp({Key key}) : super(key: key);
58
59 @override
60 _MyAppState createState() => _MyAppState();
61}
62
63class _MyAppState extends State<MyApp> {
64 Future<Dog> futureDog;
65
66 @override
67 void initState() {
68 super.initState();
69 futureDog = fetchDog();
70 }
71
72 @override
73 Widget build(BuildContext context) {
74 return MaterialApp(
75 title: 'Exemplo - Read API',
76 theme: ThemeData(
77 primarySwatch: Colors.blue,
78 ),
79 home: Scaffold(
80 appBar: AppBar(
81 title: Text('Exemplo - Read API'),
82 ),
83 body: Center(
84 child: FutureBuilder<Dog>(
85 future: futureDog,
86 builder: (context, snapshot) {
87 // Caso a API tenha retornado dados.
88 if (snapshot.hasData) {
89 // Exibe na vertical três componentes text com os dados
90 return Column(children: <Widget>[
91 Padding(
92 padding: EdgeInsets.all(20),
93 child: Text(snapshot.data.id)),
94 Padding(
95 padding: EdgeInsets.all(20),
96 child: Text(snapshot.data.name)),
97 Padding(
98 padding: EdgeInsets.all(20),
99 child: Text(snapshot.data.age.toString())),
100 Padding(
101 padding: EdgeInsets.all(20),
102 child: RaisedButton(
103 child: Text('Delete Data'),
104 onPressed: () {
105 print(deleteDog("1"));
106 }))
107 ]);
108 }
109 // Caso a API não tenha retornado os dados, mas sim lançado uma exceção.
110 else if (snapshot.hasError) {
111 return Text("${snapshot.error}");
112 }
113 // Mostra spinner enquanto carrega a requisição.
114 return CircularProgressIndicator();
115 },
116 ),
117 ),
118 ),
119 );
120 }
121}
122