How to load JSON data in Flutter?

Nitish Kumar Singh
4 min readJun 9, 2018

Flutter

In Today's world, everything is connected to the Internet. We store our data on the Internet So that we can get that data everywhere, whether it is Laptop, Mobile Phone, Browser, App etc.

To fetch data from the Internet we need to interact with the server and for that, we need an API. API is an interface which interacts with us as well as the server.

Here we will learn How we can fetch data in Flutter using API.

Let’s begin

YouTube Video for Loading JSON data in Flutter

Here we have a Hello World Program and we will start implanting from here

import 'package:flutter/material.dart';

void main() => runApp(new MyApp());

class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {

@override
Widget build(BuildContext context) {
return new MaterialApp(
home: new Scaffold(
appBar: new AppBar(
title: new Text('JSON to List'),
),
body: new Center(
child: new Text(
'Hello World !',
style: Theme.of(context).textTheme.headline,
),
),
));
}
}

We need to import two Libraries.

Update [17 Deceomber 2018 ] : You need to add http in your pubspec.yaml in order to use that. Previously it was available with flutter SDK but after Release 1.0 they remove the HTTP from flutter SDK.

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

http : http will send request to server and
convert : convert will convert the String into JSON.

Let’s make an async method which will make the request on the server and fetch the JSON data. I have also defined some Global variable so that we can update the variable inside FetchJSON and show in UI.

I have defined a bool type variable, I did this because after fetching we can easily assure that we got data from our server.

String name, username, avatar;
bool isData = false;
FetchJSON() async {
var Response = await http.get(
"https://api.github.com/users/nitishk72",
headers: {"Accept": "application/json"},
);

if (Response.statusCode == 200) {
String responseBody = Response.body;
var responseJSON = json.decode(responseBody);
username = responseJSON['login'];
name = responseJSON['name'];
avatar = responseJSON['avatar_url'];
isData = true;
setState(() {
print('UI Updated');
});
} else {
print('Something went wrong. \nResponse Code : ${Response.statusCode}');
}
}

Now call this Method in initState().

@override
void initState() {
FetchJSON();
}

After Fetching Data, It’s time to show the data in App UI.

Now again I am going to make a new Method to Show UI. I am making method because If I will write this UI code inside the build then the code will become messy.

Widget MyUI(){
return new Container(
padding: new EdgeInsets.all(20.0),
child: new ListView(
children: <Widget>[
new Image.network(
avatar,
width: 100.0,
height: 100.0,
),
new Padding(padding: new EdgeInsets.symmetric(vertical: 6.0)),
new Text(
'Name : $name',
style: Theme.of(context).textTheme.headline,
),
new Padding(padding: new EdgeInsets.symmetric(vertical: 6.0)),
new Text(
'Username : $username',
style: Theme.of(context).textTheme.title,
),
],
),
);
}

Now Its time to update the build and Show the UI. Here I am using CircularProgressIndicator because when you are fetching data from the Internet it may take some time. So it’s better to show Loading instead of Blank Screen.

@override
Widget build(BuildContext context) {
return new MaterialApp(
home: new Scaffold(
appBar: new AppBar(
title: new Text('Fetch JSON Data'),
),
body: isData
? new Center(
child: new CircularProgressIndicator(),
)
: MyUI(),
),
);
}

So, Here is your Screenshot and full code.

Flutter JSON Fetch Screenshot
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';

void main() => runApp(new MyApp());

class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
String name, username, avatar;
bool isData = false;

FetchJSON() async {
var Response = await http.get(
"https://api.github.com/users/nitishk72",
headers: {"Accept": "application/json"},
);

if (Response.statusCode == 200) {
String responseBody = Response.body;
var responseJSON = json.decode(responseBody);
username = responseJSON['login'];
name = responseJSON['name'];
avatar = responseJSON['avatar_url'];
isData = true;
setState(() {
print('UI Updated');
});
} else {
print('Something went wrong. \nResponse Code : ${Response.statusCode}');
}
}

@override
void initState() {
FetchJSON();
}

Widget MyUI() {
return new Container(
padding: new EdgeInsets.all(20.0),
child: new ListView(
children: <Widget>[
new Image.network(
avatar,
width: 100.0,
height: 100.0,
),
new Padding(padding: new EdgeInsets.symmetric(vertical: 6.0)),
new Text(
'Name : $name',
style: Theme.of(context).textTheme.headline,
),
new Padding(padding: new EdgeInsets.symmetric(vertical: 6.0)),
new Text(
'Username : $username',
style: Theme.of(context).textTheme.title,
),
],
),
);
}

@override
Widget build(BuildContext context) {
return new MaterialApp(
home: new Scaffold(
appBar: new AppBar(
title: new Text('Fetch JSON'),
),
body: isData
? new Center(
child: new CircularProgressIndicator(),
)
: MyUI(),
),
);
}
}

https://github.com/nitishk72/Flutter-Async

This is my First Article and if you like it then leave your comment and do clap to motivate me.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Nitish Kumar Singh
Nitish Kumar Singh

Written by Nitish Kumar Singh

Web🌐/ Mobile📱/ GraphQL / Cloud☁️ . Full-time programmer, part-time content creator, and Freelancer.

Responses (5)

Write a response

But how to parse Json array ?

3

how can i get int value from database

2

Also a minor issue , only if !data is loaded then show indicator
appBar: new AppBar(
title: new Text(‘Fetch JSON’),
),
body: !isData
? new Center(
child: new CircularProgressIndicator(),
)
: MyUI(),
)...

1