flutter对dio对封装(返回值泛型的处理)

需要配置FlutterJsonBeanFactory插件

 

http 请求返回集合的处理:返回 List

 void _getHomeList(int currentPage) async {
    await HttpUtil.getInstance().get(
        '${HttpUrl.HOME_PAGE_URL}name=circle&page=${_currentPage}&sort=0',
        success: (response) {
      setState(() {
        _homeList.addAll(response);
      });
    });
  }

http 请求返回对象的处理:返回 PersonDetailEntity

void _getPersonDetail(String userId, BuildContext context) async {
  //      String source=await platform.invokeMethod('getPersonDetail');
  await HttpUtil.getInstance().get(
      '${HttpUrl.HOME_DETAIL_URL}h_user_id=$userId',
      hasLoading: true,
      context: context, success: (response) {
    Navigator.push(
        context,
        MaterialPageRoute(
            builder: (context) => PersonDetailPage(entity: response)));
  });
}

这边使用了 get泛型的方式来,返回你需要的数据;

HttpResponseEntity对象

class HttpResponseEntity {
  T data;
  String flagString;
  int flag;

  HttpResponseEntity({this.data, this.flagString, this.flag});

  HttpResponseEntity.fromJson(Map json) {
    data = json['data'] != null ? EntityFactory.generateOBJ(json['data']) : null;
    flagString = json['FlagString'];
    flag = json['Flag'];
  }
}
HttpResponseListEntity对象
class HttpResponseListEntity {
  List data;
  String flagString;
  int flag;

  HttpResponseListEntity({this.data, this.flagString, this.flag});


  HttpResponseListEntity.fromJson(Map json) {
    if (json['data'] != null) {
      data = new List();
      (json['data'] as List).forEach((v) {
        data.add(EntityFactory.generateOBJ(v));
      });
    }
    flagString = json['FlagString'];
    flag = json['Flag'];
  }

}

而 EntityFactory.generateOBJ(v)正是FlutterJsonBeanFactory在自动生成代码产生的文件,无需自己写

class EntityFactory {
  static T generateOBJ(json) {
    if (1 == 0) {
      return null;
    } else if (T.toString() == "PersonDetailEntity") {
      return PersonDetailEntity.fromJson(json) as T;
    } else if (T.toString() == "NetHeaderEntity") {
      return NetHeaderEntity.fromJson(json) as T;
    } else if (T.toString() == "TextEntity") {
      return TextEntity.fromJson(json) as T;
    } else if (T.toString() == "HomeEntity") {
      return HomeEntity.fromJson(json) as T;
    } else {
      return null;
    }
  }
}

 

你可能感兴趣的:(flutter,flutter,dio,封装,flutter,泛型,flutter,返回值泛型,flutter,json,自动生成,flutter,处理,http,返回值)