Fetch JSON data from the internet in Flutter

Fetching JSON data from an API is necessary task for most apps. Fortunately, Dart and Flutter provide some built-in packages to make working with external data and read JSON string easier.

We need 2 packages, http and dart:convert, to handle this task.

  1. Make a network request using the http package.
  2. Convert JSON string to object with dart:convert.

Remember to add Internet permission for Android when using http package.

Future<http.Response> fetchTodosStatus(){
    return http.get('https://jsonplaceholder.typicode.com/todos/1');
  }
Future<Todo> fetchTodos() async{
    final response = await fetchTodosStatus();
    if (response.statusCode == 200) {
      return Todo.fromJson(jsonDecode(response.body));
    } else {
      throw Exception('Failed to load todo');
    }
  }

Todo class

class Todo {
  final int userId;
  final int id;
  final String title;
  final bool completed;

  Todo({this.userId, this.id, this.title, this.completed});

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

Leave a Comment

Your email address will not be published. Required fields are marked *

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.

Close