json_serializable.dart icon indicating copy to clipboard operation
json_serializable.dart copied to clipboard

Future data serialisation

Open HeropolisDa2ny opened this issue 1 year ago • 2 comments

Hello,

I am working with an online/offline app and I need to serialise my data at the app start up. So I have to do a trick with my images. I collect the bytes directly from the server at the data serialisation.

So here I am trying to use this converting function using a Future return type :

static Future<Uint8List>? urlToImageBytes(String url) async => http.readBytes(Uri.parse(url));

So I need to put it in the JsonKey, however fromJson doesn't accept Future.

@JsonKey(fromJson: urlToImageBytes)
final Uint8List? value;

Any idea to fix it ?

Here my versions if need :

Dart SDK version: 2.19.5 (stable) on "macos_arm64"
Flutter 3.7.8 • channel stable • https://github.com/flutter/flutter.git
Framework • revision 90c64ed42b (4 weeks ago)
Engine • revision 9aa7816315
Tools • Dart 2.19.5 • DevTools 2.20.1

HeropolisDa2ny avatar Apr 21 '23 10:04 HeropolisDa2ny

You should probably just do:

class YourClass {
  final String url;
  static Future<Uint8List>? urlToImageBytes(String url) async => http.readBytes(Uri.parse(url));
  late final Uint8List? value => urlToImageBytes(url);
}

TimWhiting avatar May 11 '23 21:05 TimWhiting

This is a potential solution for formatting the image after the serialisation but not while serialising. So this is not what I would like. I also could re-write my json['value'] with the transformed image but I also do not want that solution because it doesn't fix properly the problem.

Here the main problem is that the fromJson is made of a factory, so it cannot use async methods inside, that's why JsonKey(fromJson doesn't expect us to provide an async method.

I was asking myself why using a factory here instead of a static method returning its instance ? This could allow the usage of async methods into a fromJson. However I don't know if it is a proper solution and would requires to make a PR.

HeropolisDa2ny avatar May 12 '23 07:05 HeropolisDa2ny