如何使用 Dio 在 Flutter 中调用 API?

Qas*_*eaq 6 api dart flutter dio

我需要将 JSON 解析为对象并在我的应用程序中使用它,但我需要使用 dio 库来执行此操作,但我是新手,有人可以帮助我如何使用它来将 JSON 解析为对象,这也是我的请求需要一个令牌,我的对象将像这样锁定:

import 'dart:convert';

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

class Users {
  Users({
    this.data,
  });

  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(data.map((x) => x.toJson())),
  };
}

class Datum {
  Datum({
    this.id,
    this.name,
    this.email,
    this.phone,
    this.status,
    this.images,
  });

  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(images.map((x) => x.toJson())),
  };
}

class Image {
  Image({
    this.id,
    this.url,
    this.isProfileImage,
  });

  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,
  };
}
Run Code Online (Sandbox Code Playgroud)

任何人都可以使用 provider 和 dio 帮助我一步一步地做到这一点!

小智 6

尝试这样的事情:

  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(response.data);
      } else {
        print('${response.statusCode} : ${response.data.toString()}');
        throw response.statusCode;
      }
    } catch (error) {
      print(error);
    }
  }

... _yourClass_ data = await getData();
Run Code Online (Sandbox Code Playgroud)

如果你已经有一个令牌,你可以像这样将它添加到 dio 中:

Dio()..options.headers['authorization'] = 'Bearer $token';
Run Code Online (Sandbox Code Playgroud)

当然,这取决于授权类型。此外,如果您还没有令牌,则需要先发出请求以获取令牌(类似如上所示),然后从 response.data 中获取令牌。