123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778 |
-
- import 'dart:convert';
-
- import 'package:dio/dio.dart';
-
- class Response {
- late int code;
- String? message;
- dynamic data;
-
- Response({
- required this.code,
- this.message,
- this.data,
- });
-
- factory Response.fromJson(dynamic str) => Response.fromMap(jsonDecode(str) as Map<String, dynamic>);
-
- factory Response.fromMap(Map<String, dynamic> resp) => Response(
- code: resp['code'],
- message: resp['message'],
- data: resp['data'],
- );
- }
-
- Dio createRequest() {
- var options = BaseOptions(
- baseUrl: 'https://www.xx.com/api',
- connectTimeout: 5000,
- receiveTimeout: 3000,
- );
-
- var dio = Dio(options);
- dio.interceptors.add(InterceptorsWrapper(
- onRequest:(options, handler){
-
- return handler.next(options);
-
-
-
-
- },
- onResponse:(response,handler) {
- Response resp = Response.fromJson(response.data['data']);
- if (resp.code == 1000) {
- response.data = resp.data;
- return handler.next(response);
- } else {
- return handler.reject(response.data);
- }
- },
- onError: (DioError e, handler) {
-
- return handler.next(e);
-
-
- }
- ));
-
- return dio;
- }
-
- var instance = createRequest();
-
- Future request (RequestOptions options) async {
- var resp = await instance.fetch(options);
-
- if (resp.data.runtimeType == String) {
- String dt = resp.data as String;
- dt.trim();
- if (dt.startsWith('{') && dt.endsWith('}')) {
- return jsonDecode(dt);
- }
- return dt;
- }
-
- return resp.data;
- }
|