# 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

![](/files/-LoOGncHCLRYyq__by17)

Dar clic derecho y seleccionar

![](/files/-LoOHyUdYLofwDhGtjve)

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

![](/files/-LoOIC3CRPunORDjmfNb)

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

### Al ejecutarlo

![](/files/-LoOGEKd6iTXOcNfF2eU)

Desde un browser podemos consultar los datos

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

![](/files/-LoOGSyvao0SbMxQ5Rr5)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://avbravo-2.gitbook.io/developmentcookbook/viii.-fluter-con-restfull-api/8.1-proyecto-ejemplo.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
