How do calling API in flutter using Dio?


I need to parse JSON to object and use it in my app but I need to do this using dio library, but I’m new to it, can anybody help me how to use it to parse a JSON into an object, also my request need a token with it, my object will lock like this :

import 'dart:convert';

Users usersFromJson(String str) > Users.fromJson(json.decode(str));
String usersToJson(Users data) > json.encode(data.toJson());

class Users {

  List<Datum> data;

  factory Users.fromJson(Map<String, dynamic> json) > Users(
    data: List<Datum>.from(json["data"].map((x) > Datum.fromJson(x))),

  Map<String, dynamic> toJson() > {
    "data": List<dynamic>.from( > x.toJson())),

class Datum {

  int id;
  String name;
  String email;
  String phone;
  String status;
  List<Image> images;

  factory Datum.fromJson(Map<String, dynamic> json) > Datum(
    id: json["id"],
    name: json["name"],
    email: json["email"],
    phone: json["phone"],
    status: json["status"],
    images: List<Image>.from(json["images"].map((x) > Image.fromJson(x))),

  Map<String, dynamic> toJson() > {
    "id": id,
    "name": name,
    "email": email,
    "phone": phone,
    "status": status,
    "images": List<dynamic>.from( > x.toJson())),

class Image {

  int id;
  String url;
  int isProfileImage;

  factory Image.fromJson(Map<String, dynamic> json) > Image(
    id: json["id"],
    url: json["url"],
    isProfileImage: json["is_profile_image"],

  Map<String, dynamic> toJson() > {
    "id": id,
    "url": url,
    "is_profile_image": isProfileImage,

can any one help me step by step doing this using provider and dio please!


Try something like this:

  final client  Dio();

  Future<_yourClass_> getData() async {
    final url  'your-url';

    try {
      final response  await client.get(url);

      if (response.statusCode  200) {
        return _yourClass_.fromJson(;
      } else {
        print('${response.statusCode} : ${}');
        throw response.statusCode;
    } catch (error) {

... _yourClass_ data  await getData();

If you already has a token, you can add it into dio like this :

Dio()..options.headers['authorization']  'Bearer $token';

Of course it depends on authorization type. Also if you don’t have token already, you need to make request first to obtain a token (similar as shown above) and then get token from

Answered By – David Sedlář

Leave a Comment