Filter by Widgets


Fetch data from the internet

This Article is posted by seven.srikanth at 08-08-2018 07:57:23



Fetching data from the internet is necessary for most apps. Luckily, Dart and Flutter provide tools for this type of work!

Directions

  1. Add the http package
  2. Make a network request using the http package
  3. Convert the response into a custom Dart object
  4. Fetch and Display the data with Flutter

1. Add the http package

The http package provides the simplest way to fetch data from the internet.

To install the http package, we need to add it to the dependencies section of our pubspec.yaml. We can find the latest version of the http package on the pub website.

dependencies:
  http: <latest_version>

2. Make a network request

In this example, we’ll fetch a sample post from the JSONPlaceholder REST API using the http.get method.

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

The http.get method returns a Future that contains a Response.

  • Future is a core Dart class for working with async operations. It is used to represent a potential value or error that will be available at some time in the future.
  • The http.Response class contains the data received from a successful http call.

3. Convert the response into a custom Dart object

While it’s easy to make a network request, working with a raw Future<http.Response> isn’t very convenient. To make our lives easier, we can convert the http.Response into our own Dart object.

Create a Post class

First, we’ll need to create a Post class that contains the data from our network request. It will also include a factory constructor that allows us to create a Post from json.

Converting JSON by hand is only one option. For more information, please see the full article on JSON and serialization.

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'],
    );
  }
}

Convert the http.Response to a Post

Now, we’ll update the fetchPost function to return a Future<Post>. To do so, we’ll need to:

  1. Convert the response body into a json Map with the dart:convert package.
  2. If the server returns an “OK” response with a status code of 200, convert the json Map into a Post using the fromJson factory.
  3. If the server returns an unexpected response, throw an error
Future<Post> fetchPost() async {
  final response =
      await http.get('https://jsonplaceholder.typicode.com/posts/1');

  if (response.statusCode == 200) {
    // If server returns an OK response, parse the JSON
    return Post.fromJson(json.decode(response.body));
  } else {
    // If that response was not OK, throw an error.
    throw Exception('Failed to load post');
  }
}

Hooray! Now we’ve got a function that we can call to fetch a Post from the internet!

4. Fetch and Display the data

In order to fetch the data and display it on screen, we can use the FutureBuilder widget! The FutureBuilder Widget comes with Flutter and makes it easy to work with async data sources.

We must provide two parameters:

  1. The Future we want to work with. In our case, we’ll call our fetchPost() function.
  2. builder function that tells Flutter what to render, depending on the state of the Future: loading, success, or error.
FutureBuilder<Post>(
  future: fetchPost(),
  builder: (context, snapshot) {
    if (snapshot.hasData) {
      return Text(snapshot.data.title);
    } else if (snapshot.hasError) {
      return Text("${snapshot.error}");
    }

    // By default, show a loading spinner
    return CircularProgressIndicator();
  },
);

Testing

For information on how to test this functionality, please see the following recipes:

Complete example

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) {
    // If the call to the server was successful, parse the JSON
    return Post.fromJson(json.decode(response.body));
  } else {
    // If that call was not successful, throw an 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());

class MyApp extends StatelessWidget {
  
  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: fetchPost(),
            builder: (context, snapshot) {
              if (snapshot.hasData) {
                return Text(snapshot.data.title);
              } else if (snapshot.hasError) {
                return Text("${snapshot.error}");
              }

              // By default, show a loading spinner
              return CircularProgressIndicator();
            },
          ),
        ),
      ),
    );
  }
}

Source: https://flutter.io/cookbook/networking/fetch-data/
0 Comments
Login to comment.
Recent Comments

Be the first to Comment. You can ask a Query or Share your toughts or Just say thanks.




Recent articles

Error: The name 'RangeSlider' is defined in the libraries 'package:flutter/src/material/range_slider.dart' and 'package:flutter_range_slider/src/flutter_range_slider.dart'.

Check out this article on Error: The name 'RangeSlider' is defined in the libraries 'package:flutter/src/material/range_slider.dart' and 'package:flutter_range_slider/src/flutter_range_slider.dart'.

Read full post

How to create a persistent bottom sheet in Flutter?

Check out this article on How to create a persistent bottom sheet in Flutter?

Read full post

How to draw a Decorative Horizontal line in Flutter?

Check out this article on How to draw a Decorative Horizontal line in Flutter?

Read full post

How to fetch an Image from Internet in Flutter

Check out this article on How to fetch an Image from Internet in Flutter

Read full post

ListView with Images from the Internet

Check out this article on ListView with Images from the Internet

Read full post

How to show Tooltip in Flutter?

Check out this article on How to show Tooltip in Flutter?

Read full post

How to create BottomNavigationBar in flutter?

Check out this article on How to create BottomNavigationBar in flutter?

Read full post

How to add actions to Appbar?

Check out this article on How to add actions to Appbar?

Read full post

How to open dart devtools in VS code?

Check out this article on How to open dart devtools in VS code?

Read full post

Accessibility features in flutter

Check out this article on Accessibility features in flutter

Read full post

© 2018 - Fluttercentral | Email to me - Seven.srikanth@gmail.com

Except as otherwise noted, this work is licensed under a Creative Commons Attribution 4.0 International License , and code samples are licensed under the BSD License.