2

I am using freezed.

My code looks like this:

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);
}

This is the CancelToken class from https://github.com/flutterchina/dio/blob/master/dio/lib/src/cancel_token.dart

This does not work.

Errors:

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

How do I do this?

4

1 Answer 1

2
+50

The error is telling you that the CancelToken class cannot be converted to JSON directly. Your options are:

  1. Build a service class that converts your KeyState class into a JSON representation manually.

  2. Create an extension method for the CancelToken class in your project, which adds the fromJson and toJson methods to it. https://dart.dev/guides/language/extension-methods

  3. Fork the code from Github, add the conversion methods to the CancelToken class yourself, and reference your repo in your pubspec.yaml file. (also, submit a pull request to merge your changes into the original repo)

You will also need to add similar conversion methods for dependant types like DioError, RequestOptions, Response.

Sign up to request clarification or add additional context in comments.

4 Comments

Yes, I understand, I don't know how to do it. Can you please share how to Build a service class that converts your KeyState class into a JSON representation manually.
can you please post an example of number 2? thank you
Any workaround on this?
this is an example of a JsonConverter service: stackoverflow.com/a/69749532/13801829

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.