Parsing JSON in Flutter

Learn about getting and parsing JSON data from the internet when building a cross-platform app using Flutter. By Kevin D Moore.

Leave a rating/review
Download materials
Save for later
Share

An app without something to show on its screen is pretty boring, right? But where can you get interesting information to display on your app? From the internet, of course!

There are thousands of websites that provide information you can use to spice up your apps through REST, or Representational State Transfer, APIs, which 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 (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. Along with that information is 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 that you can display in your app. JSON stands for JavaScript Object Notation, a data format that most websites use to send data.

Note: If you’re new to Flutter, please check out our Getting Started With Flutter tutorial to for an overview of the basics of working with this SDK.

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 using the Download Materials button at the top or bottom of the page.

This tutorial will be using Android Studio with the Flutter plugin installed. 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, go to the Preferences dialog of Android Studio and find the Plugins section.

Click on the Marketplace tab and type Flutter, then click the install button. 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; go ahead and do so:

Once you’ve opened the project in Android Studio, in the device dropdown select either an Android emulator, or the iOS simulator if you are 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 on iOS,

Starter on iOS

and like this on Android,

Starter on Android

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 that 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’re going to start fixing that soon.

To start, first take a 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
  CatBreedsPage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _CatBreedsPageState 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(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:

  1. Constructs a CatBreedsPage with the title that the AppBar will use.
  2. Adds the title for the AppBar using the title field.
  3. Adds a body that uses the ListView.builder method.
  4. Sets the count to 0 for now, since you don’t have any items yet.
  5. For every card, you want to go to the CatInfo page. Here, you use the Navigator to push that card.
  6. Creates a Card widget with padding.
  7. Adds a ListTile that has a title and description.

You’ll update this UI code once you have download real data to show in it.

Using REST APIs

REST APIs consist of URLs to a server that allow you to retrieve data.

There are different methods that you can use 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 is 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 on 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 a Cats API

Head over to the Cats API sign up page now to 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 should look like this:

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

class Network {
  final String url;
  //2
  Network(this.url);

  // 3
  Future getData() async {
    print('Calling uri: $url');
    // 4
    Response response = await get(url);
    // 5
    if (response.statusCode == 200) {
      // 6
      return response.body;
    } else {
      print(response.statusCode);
    }
  }
}

Here’s what this class does:

  1. Imports the HTTP library.
  2. The Network class has a constructor that takes a string URL.
  3. Includes one asynchronous method called getData().
  4. Uses the HTTP GET method with your URL and awaits a response.
  5. Checks the status code. If it’s 200 then the response is OK. Anything else is an error.
  6. Returns the result.