Fetch and Parse Data from the Internet in Flutter [Complete Guide]

2
SHARES
2.6k
VIEWS

Today in this tutorial we will learn how to Fetch and Parse Data from the Internet in Flutter using a flutter package called “http“. Working with APIs and sending and fetching data from the internet is very necessary for apps nowadays. Most of the apps nowadays are connected through an API to a backend server. For this tutorial, we will use a Fake Json Provider “Json Placeholder” which provides fake Json data without any authentication required.

As I mentioned before, we will use the http package for this tutorial but you can also use another awesome plugin “Dio“. Dio is also a powerful Http client for Flutter, Dio supports Interceptors, Global configuration, FormData, Request Cancellation, File downloading, Timeout and much more. Let’s Start

Add the http package:

Before using the http package we’ve to install it, add it to the dependencies section of the pubspec.yaml.

dependencies:
  http: ^0.12.0+2 // we are using version 0.12.0+2

Now run flutter packages get in your terminal. This command will install this package.

Making our first HTTP call

Now we are ready to fetch data from the internet. In our code we will create a new method called getData() which will get the data from the Json Placeholder Api by using the http.get() method.

Future<http.Response> getData() {
  // we are calling the Api below and it will return a Future with type of Response
  return http.get('https://jsonplaceholder.typicode.com/posts/1');
}

Remember the http.Response class contains the data received from the http call.

Parse the Response into Dart Objects

Now after the successful http call, now we should have a post in the Json format. The next thing is to convert this json object into custom dart objects. We can also work with the raw http.response but making their own objects in much more convenient and easy.

So now we’ve to create a Post class that contains the data that came from the successful http request.

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

  Post({this.id, this.userId, 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'],
    );
  }
}

And now we’ve to update the getData() function so it returns a Future<Post>:

// import dart:convert to convert the response.body into a JSON Map
import 'dart:convert'

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

  if (response.statusCode == 200) {
    // checking if server returns an OK response, then 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 you’ve got a function that fetches a post from the internet.

With that now, we have a function that will fetch the data from the internet and then it will convert the response into custom dart objects. Now you can show that data anywhere in your app. Try utilizing this tutorial in your existing apps and make something great with the help of hundreds of openly available APIs. I hope you learned something 👍.

Best resources to learn Flutter

Leave a Reply

Your email address will not be published. Required fields are marked *

Trending