Make a HTTP GET request to get REST API JSON data into a List of Objects in Dart/Flutter

Thought I would write down the way to simple just get some data from a HTTP get call/request. I made it very simple since I realized you can use a method called from. I’ll tell you more about it as we go!

Firstly set up your http library for Flutter:

Add the http flutter library by adding http in our pubspec.yaml file under dependencies under flutter

http: ^0.12.2

Also add permissions like this to your AndroidManifest.xml file

<uses-permission android:name="android.permission.INTERNET" />

Then import http in your main.dart file at the top

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

We can now use http in dart!

I am using the todo json data from this source, if you open it up you can see that there is multiple Todo items listed. It is an array of json objects. This could obviously be anything, you might have something else. Then it is time to define a class for these items so we can keep them in a list of objects of that class type.

Let’s create a todo class file like this under the lib folder in a models (create if it doesn’t exists) folder.

TodoItem.dart

class TodoItem {
  final String title;

  TodoItem({this.title});

  factory TodoItem.fromJson(Map<String, dynamic> json) {
    return TodoItem(
      title: json['title'],
    );
  }
}

Next in our main.dart. Create Future like this.

Future<List<TodoItem>> getTodoItems() async {
  final response =
      await http.get('https://jsonplaceholder.typicode.com/todos/');
  if (response.statusCode == 200) {
    List<TodoItem> values = new List<TodoItem>.from(
        json.decode(response.body).map((data) => TodoItem.fromJson(data)));

    // lets print out the title property
    values.forEach((element) {
      print(element.title);
    });
    return values;
  } else {
    // If the server did not return a 200 OK response,
    // then throw an exception.
    throw Exception('Failed to load album');
  }
}
VS terminal window

Now when you call for the getTodoItems you will be able to see the that the console prints out the values as expected. It’s pretty cool that with a single line of code you can get the data from the http request into the List because we use from and json.decode to make it into strings, and then use fromJson with that decoded data to create objects in one go with the help of map to go through each element.

We can then access the Todo objects from the values list and return it, and work with it and what not. It is up to you what you wanna do!

0 0 votes
Article rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments