Fetching JSON data from an API is a necessary task for most apps. Fortunately, Dart and Flutter provide some built-in packages to make working with external data and reading JSON strings easier.
We need 2 packages, http
and dart:convert
, to handle this task.
- Make a network request using the
http
package. - Convert JSON string to object with
dart:convert
.
Remember to add Internet permission for Android when using the 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'], ); } }