Flutter: Fetch data from internet

Neeraj
FlutterFly
Published in
3 min readSep 13, 2023

While developing any application at some point in SDLC it becomes a mandatory task to handle data locally or from the internet. JSON is popular for lightweight format and storing and transporting data. We might need to fetch data from JSON and show it on the user interface, to accomplish this in a flutter application, we need to follow the following steps:

Add the http package

Adding http package is super easy, you just need to click here and follow instructions from there. So let's do it

As the instruction says, add the latest http dependency version to your pubspec.yaml file under the dependencies section. Remember indentation matters here so be careful. The sample is given below

If you are using Android Studio (which I will recommend you to use), click packages get to add necessary packages, or manually you can hit the command in terminal i.e “$ flutter pub get” to add packages.

Now in your project’s main.dart file import http.dart as follows

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

Network Request

To get data from the internet we need to make a request because the internet is all about making requests and getting a response from the other side. And we will do it here by writing below given lines of code

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

if (response.statusCode == 200) {
// If server returns an OK response, parse the JSON.
print(response.body);

return Post.fromJson(json.decode(response.body));
} else {
// If that response was not OK, throw an error.
throw Exception('Failed to load post');
}
}

Here we are requesting the JSON and storing its response into Post class.

Create Class

Since we are requesting and getting a response so we need something that can hold the data received from the other side, so we will make a class so that we can make dart object of what we have received, here is how we can do it

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

Fetching the Data

After making a request and storing it into a class created, the next thing we need to do is to fetch data that we need from there.

@override
void initState() {
// TODO: implement initState
super.initState();

}

Display the data

Here comes the most awaited part i.e showing data received from the internet. We are fetching everything we got in different variables and can call them wherever they needed.

getUserData() async {
Post user = await fetchPost();
setState(() {
user1 = user.userId;
id = user.id;
title = user.title;
body = user.body;
});

}

Here is the complete code on which I have explained everything.

Thanks for reading. If you found this helpful, please share it with your friends.

Did I get something wrong? Mention it in the comments. I would love to improve.
If you liked what you read, please leave some claps!

GoodBye

Thanks for reading. If you found this article to be helpful please share it with your friends.

For more about flutter, follow me, so you’ll get notified when I write new posts.

To know more about me, visit :

https://about.me/nmaurya

Follow FlutterFly :

LinkedIn : https://www.linkedin.com/in/flutterfly-5726b6189/

LinkedIn Group : https://www.linkedin.com/groups/10482289/

Facebook : https://www.facebook.com/flutterflytech/

Twitter : https://twitter.com/flutterflytech

GitHub : https://github.com/flutterflytech

Medium : https://medium.com/flutterfly-tech

Reddit : https://www.reddit.com/user/flutterflytech/

--

--