api使用dio库抖动获取响应

时间:2020-10-09 14:17:38

标签: api 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,
  };
}

任何人都可以使用提供程序和dio一步一步地帮助我!

2 个答案:

答案 0 :(得分:2)

尝试这样的事情:

  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();

如果您已经有令牌,可以像这样将其添加到dio中:

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

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

答案 1 :(得分:0)

这是一步一步的说明

首先创建一个dio API服务和服务实现类

import 'package:dio/dio.dart';

abstract class HttpService{
  void init();

  Future<Response> getRequest(String url);
}

一个Api调用实现类

import 'package:dio/dio.dart';
import 'package:getx_news_app_impl/service/http_service.dart';

const BASE_URL = "https://newsapi.org/";
const API_KEY = "fb12a31181aa4498ba52877978913275";


class HttpServiceImpl implements HttpService{

  Dio _dio;

  @override
  Future<Response> getRequest(String url) async{
    // TODO: implement getRequest

    Response response;
    try {
      response = await _dio.get(url);
    } on DioError catch (e) {
      print(e.message);
      throw Exception(e.message);
    }

    return response;
  }

  initializeInterceptors(){
    _dio.interceptors.add(InterceptorsWrapper(
      onError: (error){
        print(error.message);
      },
      onRequest: (request){
        print("${request.method} | ${request.path}");
      },
      onResponse: (response){
        print("${response.statusCode} ${response.statusMessage} ${response.data}");
      }
    ));
  }

  @override
  void init() {
    _dio = Dio(BaseOptions(
      baseUrl: BASE_URL,
      headers: {"Authorization" : "Bearer $API_KEY"}
    ));

    initializeInterceptors();
  }

}

并像这样使用该类调用 API

class NewsRepoImpl implements NewsRepo{

  HttpService _httpService;

  
  Future<List<Article>> getNewsHeadline() async{
    // TODO: implement getNewsHeadline

    try {
       final response = await _httpService.getRequest("/v2/top-headlines?country=us");

       final parsedResponse = NewsResponse.fromJson(response.data);

       return parsedResponse.articles;
    } on Exception catch (e) {
      print(e);
      return null;
    }
  }
  
}