Advertisement
joaopaulofcc

Untitled

Nov 18th, 2020 (edited)
1,073
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Dart 3.37 KB | None | 0 0
  1. import 'dart:async';
  2. import 'dart:convert';
  3. import 'package:flutter/material.dart';
  4. import 'package:http/http.dart' as http;
  5.  
  6. class 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. Future<Dog> updateDog(String name, int age) async {
  24.   final http.Response response = await http.put(
  25.     'https://5fb5817d36e2fa00166a462d.mockapi.io/dogs/1',
  26.     headers: <String, String>{
  27.       'Content-Type': 'application/json; charset=UTF-8',
  28.     },
  29.     body: jsonEncode(<String, dynamic>{
  30.       'name': name,
  31.       'age': age,
  32.     }),
  33.   );
  34.  
  35.   if (response.statusCode == 200) {
  36.     return Dog.fromJson(jsonDecode(response.body));
  37.   } else {
  38.     throw Exception('Failed to update album.');
  39.   }
  40. }
  41.  
  42.  
  43. Future<Dog> createDog(String name, int age) async {
  44.   final http.Response response = await http.post(
  45.     'https://5fb5817d36e2fa00166a462d.mockapi.io/dogs',
  46.     headers: <String, String>{
  47.       'Content-Type': 'application/json; charset=UTF-8',
  48.     },
  49.     body: jsonEncode(<String, dynamic>{
  50.       'name': name,
  51.       'age': age,
  52.     }),
  53.   );
  54.  
  55.   if (response.statusCode == 201) {
  56.     return Dog.fromJson(jsonDecode(response.body));
  57.   } else {
  58.     throw Exception('Falha ao criar um registro!');
  59.   }
  60. }
  61.  
  62. void main() => runApp(MyApp());
  63.  
  64. class MyApp extends StatefulWidget {
  65.   MyApp({Key key}) : super(key: key);
  66.  
  67.   @override
  68.   _MyAppState createState() => _MyAppState();
  69. }
  70.  
  71. class _MyAppState extends State<MyApp> {
  72.   Future<Dog> futureDog;
  73.   final TextEditingController _controller = TextEditingController();
  74.  
  75.   @override
  76.   Widget build(BuildContext context) {
  77.     return MaterialApp(
  78.       title: 'Create Data Example',
  79.       theme: ThemeData(
  80.         primarySwatch: Colors.blue,
  81.       ),
  82.       home: Scaffold(
  83.         appBar: AppBar(
  84.           title: Text('Create Data Example'),
  85.         ),
  86.         body: Container(
  87.           alignment: Alignment.center,
  88.           padding: const EdgeInsets.all(8.0),
  89.           child: (futureDog == null)
  90.               ? Column(
  91.                   mainAxisAlignment: MainAxisAlignment.center,
  92.                   children: <Widget>[
  93.                     TextField(
  94.                       controller: _controller,
  95.                       decoration: InputDecoration(hintText: 'Digite o nome'),
  96.                     ),
  97.                     RaisedButton(
  98.                       child: Text('Create Data'),
  99.                       onPressed: () {
  100.                         setState(() {
  101.                           futureDog = createDog(_controller.text, 100);
  102.                         });
  103.                       },
  104.                     ),
  105.                   ],
  106.                 )
  107.               : FutureBuilder<Dog>(
  108.                   future: futureDog,
  109.                   builder: (context, snapshot) {
  110.                     if (snapshot.hasData) {
  111.                       return Text(snapshot.data.name);
  112.                     } else if (snapshot.hasError) {
  113.                       return Text("${snapshot.error}");
  114.                     }
  115.  
  116.                     return CircularProgressIndicator();
  117.                   },
  118.                 ),
  119.         ),
  120.       ),
  121.     );
  122.   }
  123. }
  124.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement