simplezhli / flutter_deer

🦌 Flutter 练习项目(包括集成测试、可访问性测试)。内含完整UI设计图,更贴近真实项目的练习。Flutter practice project (including integration testing and accessibility testing). Contains complete UI design drawings for a more realistic practice project.
https://simplezhli.github.io/flutter_deer/
Apache License 2.0
8.01k stars 1.67k forks source link

BaseEntity解析wanAndroidAPI的错误json的null转换 #220

Closed android-1995 closed 2 years ago

android-1995 commented 2 years ago
class BaseEntity<T> {
...
  T? _generateOBJ<O>(Object json) {
    if (T.toString() == 'String') {
      return json.toString() as T;
    } else if (T.toString() == 'Map<dynamic, dynamic>') {
      return json as T;
    } else {
      /// List类型数据由fromJsonAsT判断处理
      return JsonConvert.fromJsonAsT<T>(json);
    }
  }
}

image


个人修改后的代码:

class BaseEntity<T> {
  BaseEntity(this.code, this.message, this.data);

  BaseEntity.fromJson(Map<String, dynamic> json) {
    code = json[Constant.code] as int?;
    message = json[Constant.message] as String;
    if (json.containsKey(Constant.data)) {
      data = _generateOBJ<T>(json[Constant.data] as Object?);
    }
  }

  int? code;
  late String message;
  T? data;

  T? _generateOBJ<O>(Object? json) {
    if (json == null) {
      return null;
    }
    if (T.toString() == 'String') {
      return json.toString() as T;
    } else if (T.toString() == 'Map<dynamic, dynamic>') {
      return json as T;
    } else {
      /// List类型数据由fromJsonAsT判断处理
      return JsonConvert.fromJsonAsT<T>(json);
    }
  }
}
simplezhli commented 2 years ago

@android-1995 这里确实存在这种问题。但是我使用了AdapterInterceptor将数据进行了处理,会保证data不为null。 https://github.com/simplezhli/flutter_deer/blob/c1a0bc6087a310778111b489e7f86f7e5e8d48ab/lib/net/intercept.dart#L160-L168

android-1995 commented 2 years ago
simplezhli commented 2 years ago

AdapterInterceptor的作用其实是为了兼容REST风格的API,统一用法。如果数据本身就是code、 msg、 data这种格式那么可以去掉。

data为null是需要你这样处理一下,或者说接口不返回data字段其实更好。

android-1995 commented 2 years ago

好的 好的,感谢解答

simplezhli commented 2 years ago

没事,有问题多交流。

android-1995 commented 2 years ago

还真有个问题哈 有event相关的组件吗?我看项目里好像没有类似的组件,设置页的夜间模式、多语言的值,不会及时更新

simplezhli commented 2 years ago

EventBus?flutter我记得有相关的库,但是主要还是用的状态管理。项目中的ThemeProvider 、LocaleProvider 就是做相关功能的。你说的不及时更新指的是什么。

android-1995 commented 2 years ago

我修改了夜间模式,然后返回上个界面的值没变 Screenshot_2022-09-22-10-27-09-469_com weilu deer Screenshot_2022-09-22-10-27-17-073_com weilu deer Screenshot_2022-09-22-10-27-19-906_com weilu deer

simplezhli commented 2 years ago

好吧,这是个bug。。。我抽时间修一修。

android-1995 commented 2 years ago

是通过注册ThemeProvider的监听值的变化赋值吗?

simplezhli commented 2 years ago

是的,和MyApp那里一样,套个Consumer2就行了。