· 5 years ago · Dec 19, 2020, 02:20 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 factory Dog.fromJson(Map<String, dynamic> json) {
14 return Dog(
15 id: json['id'],
16 name: json['name'],
17 age: json['age'],
18 );
19 }
20}
21
22Future<Dog> fetchDog() async {
23 final response =
24 await http.get('https://5fb5817d36e2fa00166a462d.mockapi.io/dogs/1');
25
26 if (response.statusCode == 200) {
27 return Dog.fromJson(jsonDecode(response.body));
28 }
29 else {
30 throw Exception('Falha ao carregar dados da API!');
31 }
32}
33
34Future<void> deleteDog(String id) async {
35 final http.Response response = await http.delete(
36 'https://5fb5817d36e2fa00166a462d.mockapi.io/dogs/$id',
37 headers: <String, String>{
38 'Content-Type': 'application/json; charset=UTF-8',
39 },
40 );
41
42 if (response.statusCode != 200) {
43 throw Exception('Failed ao deletar dado!');
44 }
45}
46
47void main() => runApp(MyApp());
48
49class MyApp extends StatefulWidget {
50 MyApp({Key key}) : super(key: key);
51
52 @override
53 _MyAppState createState() => _MyAppState();
54}
55
56class _MyAppState extends State<MyApp> {
57 Future<Dog> futureDog;
58
59 @override
60 void initState() {
61 super.initState();
62 futureDog = fetchDog();
63 }
64
65 @override
66 Widget build(BuildContext context) {
67 return MaterialApp(
68 title: 'Exemplo - Read API',
69 theme: ThemeData(
70 primarySwatch: Colors.blue,
71 ),
72 home: Scaffold(
73 appBar: AppBar(
74 title: Text('Exemplo - Read API'),
75 ),
76 body: Center(
77 child: FutureBuilder<Dog>(
78 future: futureDog,
79 builder: (context, snapshot) {
80 if (snapshot.hasData) {
81 return Column(children: <Widget>[
82 Padding(
83 padding: EdgeInsets.all(20),
84 child: Text(snapshot.data.id)),
85 Padding(
86 padding: EdgeInsets.all(20),
87 child: Text(snapshot.data.name)),
88 Padding(
89 padding: EdgeInsets.all(20),
90 child: Text(snapshot.data.age.toString())),
91 Padding(
92 padding: EdgeInsets.all(20),
93 child: RaisedButton(
94 child: Text('Delete Data'),
95 onPressed: () {
96 print(deleteDog("1"));
97 }))
98 ]);
99 }
100 else if (snapshot.hasError) {
101 return Text("${snapshot.error}");
102 }
103 return CircularProgressIndicator();
104 },
105 ),
106 ),
107 ),
108 );
109 }
110}
111