Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import 'dart:async';
- import 'dart:convert';
- import 'package:flutter/material.dart';
- import 'package:http/http.dart' as http;
- class Dog {
- final String id;
- final String name;
- final int age;
- Dog({this.id, this.name, this.age});
- // Método que cria um objeto Dog a partir de um JSON recebido.
- factory Dog.fromJson(Map<String, dynamic> json) {
- return Dog(
- id: json['id'],
- name: json['name'],
- age: json['age'],
- );
- }
- }
- Future<Dog> updateDog(String name, int age) async {
- final http.Response response = await http.put(
- 'https://5fb5817d36e2fa00166a462d.mockapi.io/dogs/1',
- headers: <String, String>{
- 'Content-Type': 'application/json; charset=UTF-8',
- },
- body: jsonEncode(<String, dynamic>{
- 'name': name,
- 'age': age,
- }),
- );
- if (response.statusCode == 200) {
- return Dog.fromJson(jsonDecode(response.body));
- } else {
- throw Exception('Failed to update album.');
- }
- }
- Future<Dog> createDog(String name, int age) async {
- final http.Response response = await http.post(
- 'https://5fb5817d36e2fa00166a462d.mockapi.io/dogs',
- headers: <String, String>{
- 'Content-Type': 'application/json; charset=UTF-8',
- },
- body: jsonEncode(<String, dynamic>{
- 'name': name,
- 'age': age,
- }),
- );
- if (response.statusCode == 201) {
- return Dog.fromJson(jsonDecode(response.body));
- } else {
- throw Exception('Falha ao criar um registro!');
- }
- }
- void main() => runApp(MyApp());
- class MyApp extends StatefulWidget {
- MyApp({Key key}) : super(key: key);
- @override
- _MyAppState createState() => _MyAppState();
- }
- class _MyAppState extends State<MyApp> {
- Future<Dog> futureDog;
- final TextEditingController _controller = TextEditingController();
- @override
- Widget build(BuildContext context) {
- return MaterialApp(
- title: 'Create Data Example',
- theme: ThemeData(
- primarySwatch: Colors.blue,
- ),
- home: Scaffold(
- appBar: AppBar(
- title: Text('Create Data Example'),
- ),
- body: Container(
- alignment: Alignment.center,
- padding: const EdgeInsets.all(8.0),
- child: (futureDog == null)
- ? Column(
- mainAxisAlignment: MainAxisAlignment.center,
- children: <Widget>[
- TextField(
- controller: _controller,
- decoration: InputDecoration(hintText: 'Digite o nome'),
- ),
- RaisedButton(
- child: Text('Create Data'),
- onPressed: () {
- setState(() {
- futureDog = createDog(_controller.text, 100);
- });
- },
- ),
- ],
- )
- : FutureBuilder<Dog>(
- future: futureDog,
- builder: (context, snapshot) {
- if (snapshot.hasData) {
- return Text(snapshot.data.name);
- } else if (snapshot.hasError) {
- return Text("${snapshot.error}");
- }
- return CircularProgressIndicator();
- },
- ),
- ),
- ),
- );
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement