okdio 0.1.3

  • Readme
  • Changelog
  • Example
  • Installing
  • 46

Chopper is an http client generator using source_gen and inspired by Retrofit.

Changelog #

0.1.0 #

  • update dio version

0.0.8 #

  • update dio version

0.0.4 #

  • update dio version

0.0.3 #

  • update dio version

0.0.2 #

  • update dio version

0.0.1 #

  • Initial version, created by Stagehand

example/main.dart

import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:logger/logger.dart';
import 'package:dio/adapter.dart';
import 'package:okdio/okdio.dart';
import 'package:okdio/src/interceptor.dart';
import 'definition.dart';
import 'package:rxdart/rxdart.dart';
import 'package:dio/dio.dart';
import 'json/person.dart';
import 'package:pretty_dio_logger/pretty_dio_logger.dart';

var logger = Logger(
  printer: PrettyPrinter(),
);
class LogSetting extends LogFilter{
  @override
  bool shouldLog(LogEvent event) {
    return true;
  }

}
var loggerNoStack = Logger(
  filter: LogSetting(),
  printer: PrettyPrinter(
      methodCount: 20, // number of method calls to be displayed
      errorMethodCount: 8, // number of method calls if stacktrace is provided
      lineLength: 120, // width of the output
      colors: true, // Colorful log messages
      printEmojis: true, // Print an emoji for each log message
      printTime: false // Should each log print contain a timestamp
      ),
);
main() async {
  print(1);
//  init();
  print(2);
  const bool inProduction = const bool.fromEnvironment("dart.vm.product"); //release == true
  print(inProduction);
  final chopper = ChopperClient(
      baseUrl: "http://mockserver",
      services: [
        // the generated service
        MyService.create()
      ],
      onSendProgress: (int sent, int total) {
        print("$sent, $total");
      },
      adapter: MockAdapter(),
      errorConverter: (error) {
//        print("Error Happend: type:${error.type}, status[${error.response?.statusCode}]");
//        switch(error.type) {
//          case DioErrorType.DEFAULT:
//            error.message = "网络出错啦";
//            break;
//          case DioErrorType.CANCEL:
//            error.message = "";
//            break;
//          case DioErrorType.CONNECT_TIMEOUT:
//            error.message = "连接超时";
//            break;
//          case DioErrorType.RECEIVE_TIMEOUT:
//            error.message = "网络超时";
//            break;
//          case DioErrorType.SEND_TIMEOUT:
//            error.message = "网络超时";
//            break;
//          case DioErrorType.RESPONSE:
//            int code = error.response.statusCode;
//            if (code >= 400 && code < 500) {
//              error.message = "客户端错误的请求";
//            } else if (code >= 500 && code < 700) {
//              error.message = "服务器发生错误";
//            }
//            break;
//        }
        return ChopperError(error, "服务器发生错误");
      },
      iterable: <Interceptor>[
        InterceptorsWrapper(onRequest: (RequestOptions options) {
          print("head test");
          options.headers["MyHead"] = "head test";
        }),
        PrettyDioLogger(
            responseBody: !inProduction,
            requestHeader: !inProduction,
            request: !inProduction,
            requestBody: !inProduction,
            responseHeader: !inProduction,
            maxWidth: 220,
            compact: true,
            error: !inProduction),
        //CookieManager(CookieJar())
      ]);
  print(4);
//  var l = ()=>List<Person>();
  final myService = chopper.service<MyService>(MyService);

//  final response = await myService.getResourceAll4(UploadFileInfo(File(""), "1"));
//  response.listen((p) {
//    print(p["name"].p.p2.name);
//  }, onError: (e) {
//    print("onError $e");
//  });
//
//  final response2 = await myService.getResourceAll23();
//  response2.listen((p) {
//    print(p.body.name);
//    print(p.body.p2.name);
//    //print(p.body.p.p2.name);
//  }, onError: (e) {
//    print("onError $e");
//  });

//  myService.getResourceAll71().doOnCancel(onCancel)

//  final response4 = await myService.getResourceAll71();
//  response4
//      .doOnListen(() => logger.wtf("Log message with 2 methods"))
//      .doOnListen(() => loggerNoStack.w("Just a warning!"))
//      .doOnDone(() => Logger(printer: SimplePrinter()..useColor = true).v("boom"))
//      .doOnDone(() => print(400))
//      .doOnData((i) => print("500-$i"))
//      .transform(DoStreamTransformer(onListen: () => print("start"), onDone: () => print("end")))
//      .listen((p) {
//    print(p.p2[0].name);
//    //print(p[1].p2.name);
//    //print(p.body.p.p2.name);
//  }, onError: (e) {
//    print("onError $e");
//  });
//
//  final response3 = await myService.getResourceAll3();
//  response3.listen((p) {
//    print(p.body.name);
//    print(p.body.p2.name);
//    //print(p.body.p.p2.name);
//  }, onError: (e) {
//    print("onError $e");
//  });
//  final response31 = await myService.getResourceAll3();
//  response31.listen((p) {
//    print(p.body.name);
//    print(p.body.p2.name);
//    //print(p.body.p.p2.name);
//  }, onError: (e) {
//    print("onError $e");
//  });
//  final response32 = await myService.getResourceAll3();
//  response32.listen((p) {
//    print(p.body.name);
//    print(p.body.p2.name);
//    //print(p.body.p.p2.name);
//  }, onError: (e) {
//    print("onError $e");
//  });
//  final response33 = await myService.getResourceAll3();
//  response33.listen((p) {
//    print(p.body.name);
//    print(p.body.p2.name);
//    //print(p.body.p.p2.name);
//  }, onError: (e) {
//    print("onError $e");
//  });
  final response34 = await myService.getResourceAll41();
  response34.doOnError((e, s) {}).transform(StreamTransformer.fromHandlers()).onErrorReturn(Map()).listen((p) {
//    print(p.body.name);
//    print(p.body.p2.name);
    //print(p.body.p.p2.name);
  });
//
//  myService.getResourceAll5().listen((d) {
//    print(d[0].name);
//  });
//
//  //Person<Person3, Per..n()son3>()..p=Person3();
//
//  List<int> l = [1, 2, 3];
//  print(l is List);

  chopper.dispose();
}

class MockAdapter extends HttpClientAdapter {
  static const String mockHost = "mockserver";
  static const String mockBase = "http://$mockHost";
  DefaultHttpClientAdapter _defaultHttpClientAdapter = DefaultHttpClientAdapter();

  @override
  Future<ResponseBody> fetch(RequestOptions options, Stream<List<int>> requestStream, Future cancelFuture) async {
    Uri uri = options.uri;
    if (uri.host == mockHost) {
      print(uri.path);
      switch (uri.path) {
        case "/test--":
          return ResponseBody.fromString(
            jsonEncode({
              "index": 0,
              "name": "mock", //{"path": uri.path}
              "p": {
                "index": 1,
                "name": "mock2----", //{"path": uri.path}
                "p2": {
                  "index": 1,
                  "name": "mock3----2222222--", //{"path": uri.path}
                }
              },
              "p2": {
                "index": 1,
                "name": "mock344444------", //{"path": uri.path}
              }
            }),
            200,
            headers: {
              HttpHeaders.contentTypeHeader: [Headers.jsonContentType],
            },
          );
        case "/test2":
          return ResponseBody.fromString(
            jsonEncode({
              "name": {
                "p": {
                  "index": 1,
                  "name": "mock2----", //{"path": uri.path}
                  "p2": {
                    "index": 1,
                    "name": "mock3---vvvvv---", //{"path": uri.path}
                  }
                },
                "p2": {
                  "index": 1,
                  "name": "mock3------", //{"path": uri.path}
                }
              }, //{"path": uri.path}
            }),
            200,
            headers: {
              HttpHeaders.contentTypeHeader: [Headers.jsonContentType],
            },
          );
        case "/test12":
          return ResponseBody.fromString(
            jsonEncode({
              "index": 0,
              "name": "mock", //{"path": uri.path}

              "p2": null,
            }),
            200,
            headers: {
              HttpHeaders.contentTypeHeader: [Headers.jsonContentType],
            },
          );
        case "/test42":
          return ResponseBody.fromString(
            jsonEncode({
              "name": {
                "index": 1,
                "name": "mock344444------", //{"path": uri.path}
                "hh": "---"
              }
            }),
            200,
            headers: {
              HttpHeaders.contentTypeHeader: [Headers.jsonContentType],
            },
          );
        case "/test71":
          return ResponseBody.fromString(
            jsonEncode({
              "name": "",
              "p2": [
                {"name": "hhhh"}
              ]
            }),
            200,
            headers: {
              HttpHeaders.contentTypeHeader: [Headers.jsonContentType],
            },
          );
        case "/test4":
          return ResponseBody.fromString(
            jsonEncode([
              {
                "index": 0,
                "name": "mock", //{"path": uri.path}
                "p": {
                  "index": 1,
                  "name": "mocddddk344444------", //{"path": uri.path}
                },
                "p2": {
                  "index": 1,
                  "name": "mock344444------", //{"path": uri.path}
                }
              },
              {
                "index": 0,
                "name": "4mock", //{"path": uri.path}
                "p": {
                  "index": 1,
                  "name": "3mocddddk344444------", //{"path": uri.path}
                },
                "p2": {
                  "index": 1,
                  "name": "3mock344444------", //{"path": uri.path}
                }
              }
            ]),
            200,
            headers: {
              HttpHeaders.contentTypeHeader: [Headers.jsonContentType],
            },
          );
        case "/download":
          return ResponseBody(
            File("./README.MD").openRead(),
            200,
            headers: {
              HttpHeaders.contentTypeHeader: [Headers.jsonContentType],
            },
          );

        case "/token":
          {
            var t = "ABCDEFGHIJKLMN".split("")..shuffle();
            return ResponseBody.fromString(
              jsonEncode({
                "errCode": 0,
                "data": {"token": t.join()}
              }),
              200,
              headers: {
                HttpHeaders.contentTypeHeader: [Headers.jsonContentType],
              },
            );
          }
        default:
          return ResponseBody.fromString("", 404);
      }
    }
    return _defaultHttpClientAdapter.fetch(options, requestStream, cancelFuture);
  }

  @override
  void close({bool force = false}) {
    // TODO: implement close
  }
}

Use this package as a library

1. Depend on it

Add this to your package's pubspec.yaml file:


dependencies:
  okdio: ^0.1.3

2. Install it

You can install packages from the command line:

with pub:


$ pub get

with Flutter:


$ flutter pub get

Alternatively, your editor might support pub get or flutter pub get. Check the docs for your editor to learn more.

3. Import it

Now in your Dart code, you can use:


import 'package:okdio/okdio.dart';
  
Popularity:
Describes how popular the package is relative to other packages. [more]
0
Health:
Code health derived from static analysis. [more]
88
Maintenance:
Reflects how tidy and up-to-date the package is. [more]
100
Overall:
Weighted score of the above. [more]
46
Learn more about scoring.

We analyzed this package on Mar 27, 2020, and provided a score, details, and suggestions below. Analysis was completed with status completed using:

  • Dart: 2.7.1
  • pana: 0.13.6

Health suggestions

Fix lib/src/annotations.dart. (-6.31 points)

Analysis of lib/src/annotations.dart reported 13 hints, including:

line 15 col 17: Use = to separate a named parameter from its default value.

line 77 col 39: Use = to separate a named parameter from its default value.

line 77 col 58: Use = to separate a named parameter from its default value.

line 84 col 25: Use = to separate a named parameter from its default value.

line 84 col 59: Use = to separate a named parameter from its default value.

Fix lib/src/request.dart. (-3.45 points)

Analysis of lib/src/request.dart reported 7 hints, including:

line 1 col 8: Unused import: 'dart:async'.

line 25 col 20: Use = to separate a named parameter from its default value.

line 26 col 17: Use = to separate a named parameter from its default value.

line 27 col 19: Use = to separate a named parameter from its default value.

line 28 col 15: Use = to separate a named parameter from its default value.

Fix lib/src/base.dart. (-1.49 points)

Analysis of lib/src/base.dart reported 3 hints:

line 54 col 17: Use = to separate a named parameter from its default value.

line 60 col 38: Use = to separate a named parameter from its default value.

line 83 col 28: The declaration '_decodeResponse' isn't referenced.

Fix lib/src/response.dart. (-1 points)

Analysis of lib/src/response.dart reported 2 hints:

line 1 col 8: Unused import: 'dart:io'.

line 16 col 36: Avoid shadowing type parameters.

Format lib/src/interceptor.dart.

Run dartfmt to format lib/src/interceptor.dart.

Dependencies

Package Constraint Resolved Available
Direct dependencies
Dart SDK >=2.0.0 <3.0.0
dio ^3.0.8 3.0.9
dson ^0.16.0 0.16.0
logging ^0.11.3 0.11.4
meta ^1.1.8 1.1.8
rxdart ^0.23.1 0.23.1 0.24.0-dev.1
Transitive dependencies
_fe_analyzer_shared 1.0.3
analyzer 0.39.4
args 1.6.0
async 2.4.1
build 1.2.2
built_mirrors 0.11.0
charcode 1.1.3
collection 1.14.12
convert 2.1.1
crypto 2.1.4
csslib 0.16.1
dart_style 1.3.3
glob 1.2.0
html 0.14.0+3
http_parser 3.1.4
js 0.6.1+1
node_interop 1.0.3
node_io 1.0.1+2
package_config 1.9.3
path 1.6.4
pedantic 1.9.0
pub_semver 1.4.4
serializable 0.12.0
source_gen 0.9.5
source_span 1.7.0
string_scanner 1.0.5
term_glyph 1.1.0
typed_data 1.1.6
watcher 0.9.7+14
yaml 2.2.0
Dev dependencies
build_runner ^1.7.4
build_web_compilers any
coverage ^0.13.5
logger ^0.8.3
okdio_generator
pretty_dio_logger ^1.1.0
test ^1.12.0