Retrieving Json Data in Flutter

Emine İNAN
HardwareAndro
Published in
2 min readOct 20, 2020
Image Source

In this tutorial we will retrieve json data in Flutter using HTTP package.

What does HTTP package do?

The HTTP package is used to retrieve data from the internet.

In this example, we will list the Breaking Bad characters on the screen.

Step 1

Create a Flutter project.

Step 2

Go to pubspec.yaml file and add http package under dependencies. (You can find the package here.)

pubspec.yaml

Step 3

Create a model folder under the lib folder to keep data. Then open a file named character.dart under the model folder.

First, open a Character class in this file and add the required properties: id, name, img and nickname.

Then, use the constructor named Character.fromJson to convert the Json data to character object.

Finally, create a Map type function named toJson to convert the character object to json format.

lib/model/character.dart

Step 4

Create a data folder under the lib folder. Then, under the data folder, open a file named characterr_api.dart to keep api.

Open a class named CharacterApi and import Http into that class.

To use a function that returns Future, import the async library.

Async means that this function is asynchronous and you need to wait to get its result. Future is a type that comes from the future and returns value from your asynchronous function.

Create a Future type function called getCharacters and fetch the data from the Internet with the help of Http get method. (You can find the API here.)

lib/data/character_api.dart

Step 5

Create a screens folder under the lib folder. Then, under the screens folder, open a file named character_list.dart to list characters.

Create a StatefulWidget.

lib/screens/character_list.dart

Define a list called CharacterList to hold the characters.

characterList

When we send a request, we call the incoming response, the data, “response”.

then method is used to capture results once the operation is completed.

Use the setState function to update the state variable.

An Iterable is a collection of elements that can be accessed sequentially.

json.decode is used to decode the JSON data into the Dart Map object. Once JSON data is decoded, it will be converted into List<Character>.

getCharactersfromApi

Call the getCharactersfromApi() method in the initState() method. The initState() method is called exactly once and then never again.

initState()

Use ListView widget to show list items and ListTile to show each element.

ListView.builder()

The complete code of the character_list.dart is as follows.

lib/screens/character_list.dart

Program output.

ProgramOutput

Thank you for reading.

To access the finished project on GitHub:

--

--

Emine İNAN
HardwareAndro

Android Developer by day, Android Developer by night. @Huawei