> For the complete documentation index, see [llms.txt](https://avbravo-2.gitbook.io/developmentcookbook/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://avbravo-2.gitbook.io/developmentcookbook/viii.-fluter-con-restfull-api/8.1-proyecto-ejemplo.md).

# 8.1 Proyecto ejemplo

Basado en el tutorial

{% embed url="<https://flutter-es.io/docs/cookbook/networking/fetch-data>" %}

Crear un proyecto nuevo

Agregar la dependencia

```dart
http: 0.12.0
```

### Editar el archivo pubsec,yaml y agregar la dependencia

![](https://547521780-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-Lc1Wg6HsWAzyOSRs0Cb%2F-LoOIkM5WylXoTMyEU9d%2F-LoOGncHCLRYyq__by17%2Fge.png?alt=media\&token=8d69a87c-05fb-458e-87e7-e5e52ed8e79d)

Dar clic derecho y seleccionar

![](https://547521780-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-Lc1Wg6HsWAzyOSRs0Cb%2F-LoOIkM5WylXoTMyEU9d%2F-LoOHyUdYLofwDhGtjve%2Fget.png?alt=media\&token=ccba379a-a340-43c6-b527-761b1ad0ae64)

Hacer una petición por red

```dart
Future<http.Response> fetchPost() {
  return http.get('https://jsonplaceholder.typicode.com/posts/1');
}
```

La respuesta debe ser convertido a un objeto Dart., generlamente creamos una clase.

Convertir el http.Response en un Post.

Usar el Widget  FutureBuilder para mostrar los datos.

Reemplazar main.dart con

```dart
import 'dart:async';
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

Future<Post> fetchPost() async {
  final response =
      await http.get('https://jsonplaceholder.typicode.com/posts/1');

  if (response.statusCode == 200) {
    // Si la llamada al servidor fue exitosa, analiza el JSON
    return Post.fromJson(json.decode(response.body));
  } else {
    // Si la llamada no fue exitosa, lanza un error.
    throw Exception('Failed to load post');
  }
}

class Post {
  final int userId;
  final int id;
  final String title;
  final String body;

  Post({this.userId, this.id, this.title, this.body});

  factory Post.fromJson(Map<String, dynamic> json) {
    return Post(
      userId: json['userId'],
      id: json['id'],
      title: json['title'],
      body: json['body'],
    );
  }
}

void main() => runApp(MyApp(post: fetchPost()));

class MyApp extends StatelessWidget {
  final Future<Post> post;

  MyApp({Key key, this.post}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Fetch Data Example',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Scaffold(
        appBar: AppBar(
          title: Text('Fetch Data Example'),
        ),
        body: Center(
          child: FutureBuilder<Post>(
            future: post,
            builder: (context, snapshot) {
              if (snapshot.hasData) {
                return Text(snapshot.data.title);
              } else if (snapshot.hasError) {
                return Text("${snapshot.error}");
              }

              // Por defecto, muestra un loading spinner
              return CircularProgressIndicator();
            },
          ),
        ),
      ),
    );
  }
```

Ejecute Genymotion y el Device respectivo

![](https://547521780-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-Lc1Wg6HsWAzyOSRs0Cb%2F-LoOIkM5WylXoTMyEU9d%2F-LoOIC3CRPunORDjmfNb%2Fred.png?alt=media\&token=3fd4e7cc-9907-483a-a75e-a788bfac7ead)

Una vez que el emulador este en ejecución ejecute el proyecto desde Visual Studio Code.

### Al ejecutarlo

![](https://547521780-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-Lc1Wg6HsWAzyOSRs0Cb%2F-LoOIkM5WylXoTMyEU9d%2F-LoOGEKd6iTXOcNfF2eU%2Femulator.png?alt=media\&token=6c5174ad-86d2-4ee7-a374-15ac377b3683)

Desde un browser podemos consultar los datos

<https://jsonplaceholder.typicode.com/posts/1>

![](https://547521780-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-Lc1Wg6HsWAzyOSRs0Cb%2F-LoOIkM5WylXoTMyEU9d%2F-LoOGSyvao0SbMxQ5Rr5%2Fjson.png?alt=media\&token=1decefcc-3b20-49fd-beda-71758cc3f3c0)
