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.

Leave a rating/review
Download materials
Save for later
Share
Update note: Sardor Islomov updated this tutorial for Flutter 3.7.5. Kevin Moore wrote the original.

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.
Note: If you’re new to Flutter, please check out our Getting Started With Flutter tutorial for an overview of the basics of working with this SDK.

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.

Plugins in Android Studio

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.

Open flutter project

Select file

Android Studio may prompt you to fetch the packages needed for the project. If so, click Get dependencies.

Starter project get dependency

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.

Run starter project

The starter app will show an empty screen like this:

iOS Start run result

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:

  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’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.

Note: You can learn more about HTTP and HTTP methods on the MDN HTTP documentation page

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:

  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. Fetches cat data using 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.