In this example, we will list the Breaking Bad characters on the screen.
Create a Flutter project.
Go to pubspec.yaml file and add http package under dependencies. (You can find the package here.)
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.
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.)
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.
Define a list called CharacterList to hold the characters.
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>.
Call the getCharactersfromApi() method in the initState() method. The initState() method is called exactly once and then never again.
Use ListView widget to show list items and ListTile to show each element.
The complete code of the character_list.dart is as follows.
Thank you for reading.
To access the finished project on GitHub: