Flutter之dio网络请求--生成bean

At First

  引入dio以及jsonAnnotation做数据解析使用。

dependencies:
  flutter:
    sdk: flutter
  	cupertino_icons: ^0.1.2
  	json_annotation: ^2.0.0
  	dio: ^1.0.6

dev_dependencies:
  flutter_test:
    sdk: flutter
  json_serializable: ^2.0.0
  build_runner: ^1.0.0
2、在项目根目录创建build.yaml文件,用于构件项目时自动生成代码。
targets:
  $default:
    builders:
      json_serializable:
        options:
          # Options configure how source code is generated for every
          # `@JsonSerializable`-annotated class in the package.
          #
          # The default value for each is listed.
          #
          # For usage information, reference the corresponding field in
          # `JsonSerializableGenerator`.
          any_map: false
          checked: false
          create_factory: true
          create_to_json: true
          disallow_unrecognized_keys: false
          explicit_to_json: false
          field_rename: none
          generate_to_json_function: true
          include_if_null: true
          nullable: true
          use_wrappers: false
3、接下来就是生产bean以及解析赋值了

习惯了Java代码构建一个bean类,所以老想着也弄一个,这样调用起来方便一点。因此,可以使用这个大佬的 工具 自动生成dart文件,我这里调用了wanandroid的注册接口,如下:Flutter之dio网络请求--生成bean_第1张图片

生成dart文件直接拷贝过去,然后在项目的根目录按住shift+鼠标右键,选择打开powerShell窗口,输入如下命令:

flutter packages pub run build_runner build

运行完成后,就会生成一个 register_response.g.dart文件
在这里插入图片描述

这样我们的实体类就构建完成了。

4、Others

下面附上网络请求工具类,希望能给你灵感

import 'package:dio/dio.dart';

import 'urls.dart';

class NetUtil {
  static const String GET = "get";
  static const String POST = "post";

  static Future get(String url, Function callBack,
      [dynamic params, Function errorCallBack]) async {
    return _request(Urls.baseUrl + url, callBack,
        method: GET, params: params, errorCallBack: errorCallBack);
  }

  static Future post(String url, Function callBack,
      [dynamic params, Function errorCallBack]) async {
    return _request(Urls.baseUrl + url, callBack,
        method: POST, params: params, errorCallBack: errorCallBack);
  }

  //公共代码部分具体的还是要看返回数据的基本结构
  static Future _request(String url, Function callBack,
      {String method, dynamic params, Function errorCallBack}) async {
    print(" url :<" + method + ">" + url);

    if (params != null && params.isNotEmpty) {
      print(" params :" + params.toString());
    }

    int statusCode;

    Response response;
    try {
      if (method == GET) {
        //组合GET请求的参数
        if (params != null && params is Map && params.isNotEmpty) {
          StringBuffer sb = new StringBuffer("?");
          params.forEach((key, value) {
            sb.write("$key" + "=" + "$value" + "&");
          });
          String paramStr = sb.toString();
          paramStr = paramStr.substring(0, paramStr.length - 1);
          url += paramStr;
        }
        response = await Dio().get(url);
      } else {
        if (params != null && params.isNotEmpty) {
          response = await Dio().post(url, data: params);
        } else {
          response = await Dio().post(url);
        }
      }
    } catch (exception) {
      _handError(errorCallBack, statusCode);
      return Future.value();
    }

    statusCode = response.statusCode;
    var result = response.data;

    //处理错误部分
    if (statusCode != 200) {
      _handError(errorCallBack, statusCode);
    }

    if (callBack != null) {
      callBack(result);
      print(" response data:" + result.toString());
    }
  }

  //处理异常
  static void _handError(Function errorCallback, int statusCode) {
    print(" statusCode :$statusCode");
    errorCallback("网络连接失败");
  }
}
How to use

这里主要传递了两个回调函数,当然由于我们的NetUtil类是用的[],所以不是必填项。

FormData formData = new FormData.from(
          {"username": username, "password": password, "repassword": rePass});
      NetUtil.post(
          C.registerUrl,
          (result) {
            RegisterResponse response = RegisterResponse.fromJson(result);
            Utils.showToast(response.errorMsg);
          },
          formData,
          (errorMsg) {
            Utils.showToast(errorMsg);
          });

附上结果图:

结果

你可能感兴趣的:(Flutter)