Parsing JSON in Flutter
Learn about getting and parsing JSON data from the internet when building a cross-platform app using Flutter. By Sardor Islomov.
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress, bookmark, personalise your learner profile and more!
Create accountAlready a member of Kodeco? Sign in
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress, bookmark, personalise your learner profile and more!
Create accountAlready a member of Kodeco? Sign in
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress, bookmark, personalise your learner profile and more!
Create accountAlready a member of Kodeco? Sign in
Contents
Parsing JSON in Flutter
25 mins
- Getting Started
- Understanding the UI
- Using REST APIs
- Signing Up for the Cats API
- Making Network Calls
- Understanding JSON
- Parsing JSON
- By Hand
- Using Libraries
- The Cat API
- Using the Cat API
- Creating Models
- Using JSON Annotations
- JSON Conversion Methods
- Using build_runner
- Error Handling
- Using the Models
- Building the Cat Detail Page
- Where to Go From Here?
An app without something to show on its screen is pretty boring, right? But where can you get interesting information to display in your app? From the internet, of course!
Thousands of websites can provide information that lets you spice up your apps through REST, or representational state transfer, APIs. These APIs define a way to implement web services. Many sites allow you to create an account to access resources like images, data and more through REST APIs.
In this tutorial, you’ll sign up for a website that provides information about cats, and you’ll build a Flutter app to display that information — and for you dog lovers out there, there are dog APIs as well. You’ll get a list of cat breeds along with information about each breed. That information also includes an image you can display that shows how each cat breed looks.
But once you get that information, how do you put it on your app’s screen? This tutorial will also show you how to parse JSON data into model classes you can display in your app. JSON stands for JavaScript Object Notation, a data format that most websites use to send data.
In this tutorial, you’ll see how Flutter implements the following:
- Calling network APIs.
- Parsing JSON data.
- Showing JSON data in a ListView.
- Displaying network images.
Getting Started
Download the starter project for this tutorial by clicking Download materials at the top or bottom of the page.
This tutorial uses Android Studio with the Flutter plugin installed. However, you can also use Visual Studio Code, IntelliJ IDEA or a text editor of your choice with Flutter at the command line.
To install the Flutter plugin, open Android Studio and find the Plugins section.
Click the Marketplace tab and type Flutter, then click Install. You may also need to install other plugins like Dart, but installing the Flutter plugin should install the other needed plugins for you.
With the plugins installed, open the starter project in Android Studio by choosing Open an existing Android Studio project and finding the root folder of the starter project zip file.
Android Studio may prompt you to fetch the packages needed for the project. If so, click Get dependencies.
Once you’ve opened the project in Android Studio, in the device dropdown, select either an Android emulator or the iOS simulator if you’re on a Mac and have Xcode installed. Then, press Control-R or click the green Run button to build and run the starter project.
The starter app will show an empty screen like this:
In this tutorial, you’ll build on the starter project to first load a set of cat breeds with a short description of each breed. Then, you’ll update the list of breeds, so clicking on a row takes the user to an image of a cat from that breed.
Understanding the UI
Right now, you can’t see anything on the screen because your app has no data. You’ll start fixing that soon.
First, look at the code that builds the UI. Open cat_breeds.dart in the lib/screens folder, which contains the following code:
import 'package:flutter/material.dart';
import 'cat_info.dart';
class CatBreedsPage extends StatefulWidget {
// 1
const CatBreedsPage({Key key, this.title}) : super(key: key);
final String title;
@override
State<CatBreedsPage> createState() => _CatBreedsPageState();
}
class _CatBreedsPageState extends State<CatBreedsPage> {
@override
void initState() {
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
// 2
title: Text(widget.title),
),
// 3
body: ListView.builder(
// 4
itemCount: 0,
itemBuilder: (context, index) {
// 5
return GestureDetector(
onTap: () {
Navigator.push<void>(context,
MaterialPageRoute(builder: (context) {
return CatInfo(catId: 'id', catBreed: 'Name');
}));
},
// 6
child: Card(
child: Padding(
padding: const EdgeInsets.all(8.0),
// 7
child: ListTile(
title: Text('Breed Name'),
subtitle: Text('Breed Description'),
),
),
),
);
}),
);
}
}
Here’s a description of what each section does:
- Constructs a
CatBreedsPage
with the title that theAppBar
will use. - Adds the title for the AppBar using the
title
field. - Adds a body that uses the
ListView.builder
method. - Sets the count to 0 for now since you don’t have any items yet.
- For every card, you want to go to the
CatInfo
page. Here, you use theNavigator
to push that card. - Creates a
Card
widget with padding. - Adds a
ListTile
that has a title and description.
You’ll update this UI code once you’ve downloaded real data to show in it.
Using REST APIs
REST APIs consist of URLs to a server that allow you to save, modify and retrieve data.
You can use a few different HTTP methods with REST APIs. The most common method you’ll use is GET, which retrieves data rather than saving it. In addition, you can use POST for saving and PATCH or PUT for updating. There’s also a DELETE method for deleting.
If you go to the documentation page of the Cats API, you’ll see all of the different calls you can make. If you click the Search by Breed link, you’ll see that you need an API key to complete the action.
You can also see that the API looks like this: https://api.thecatapi.com/v1/images/search?breed_ids={breed-id} where {breed-id}
stands for the ID of the breed to search.
Signing Up for the Cats API
Head over to the Cats API page and sign up for an account.
You must sign up and get a key since you’d only be able to make a few calls without the key.
Making Network Calls
Making network calls is easy in Dart. All you have to do is use the HTTP library from the starter project. Open network.dart in the lib/api folder. It looks like this:
// 1
import 'package:http/http.dart';
class Network {
final String URL;
// 2
Network(this.url);
// 3
Future<String> getData() async {
// 4
final response = await get(Uri.parse(url));
// 5
if (response.statusCode == 200) {
// 6
return response.body;
} else {
return '';
}
}
}
Here’s what this class does:
- Imports the HTTP library.
- The
Network
class has a constructor that takes a string URL. - Includes one asynchronous method called
getData()
. - Fetches cat data using the HTTP GET method with your URL and awaits a response.
- Checks the status code. If it’s 200, then the response is OK. Anything else is an error.
- Returns the result.