2

我在用freezed.

我的代码如下所示:

import 'package:freezed_annotation/freezed_annotation.dart';

part 'key_state.freezed.dart';
part 'key_state.g.dart';

@freezed
class KeyState with _$KeyState {
  factory KeyState({
    CancelToken? token,
    // ...
  }) = _KeyState;

  factory KeyState.initial() => KeyState();

  factory KeyState.fromJson(Map<String, dynamic> json) =>
      _$KeyStateFromJson(json);
}

这是CancelToken来自https://github.com/flutterchina/dio/blob/master/dio/lib/src/cancel_token.dart的课程

这不起作用。

错误:

Could not generate `fromJson` code for `token`.
To support the type `CancelToken` you can:
* Use `JsonConverter`
  https://pub.dev/documentation/json_annotation/latest/json_annotation/JsonConverter-class.html
* Use `JsonKey` fields `fromJson` and `toJson`
  https://pub.dev/documentation/json_annotation/latest/json_annotation/JsonKey/fromJson.html
  https://pub.dev/documentation/json_annotation/latest/json_annotation/JsonKey/toJson.html
package:flutter_app/redux/state/key_state.freezed.dart:114:22

我该怎么做呢?

4

1 回答 1

2

该错误告诉您 CancelToken 类不能直接转换为 JSON。您的选择是:

  1. 构建一个将您的 KeyState 类手动转换为 JSON 表示的服务类。

  2. 在项目中为 CancelToken 类创建一个扩展方法,将 fromJson 和 toJson 方法添加到其中。 https://dart.dev/guides/language/extension-methods

  3. 从 Github 分叉代码,自己将转换方法添加到 CancelToken 类,并在 pubspec.yaml 文件中引用您的 repo。(另外,提交拉取请求以将您的更改合并到原始存储库中)

您还需要为依赖类型(如 DioError、RequestOptions、Response)添加类似的转换方法。

于 2021-08-01T21:19:05.483 回答