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

How should I reference a serializable type in a generic?

Open hamishjohnson opened this issue 2 years ago • 1 comments

flutter --version

Flutter 2.10.3 • channel stable • https://github.com/flutter/flutter.git
Framework • revision 7e9793dee1 (3 weeks ago) • 2022-03-02 11:23:12 -0600
Engine • revision bd539267b4
Tools • Dart 2.16.1 • DevTools 2.9.2

Is it really an issue? For general questions consider starting with Stack Overflow: I tried this but got no response, figured I'd try here instead. Anyway, if it's possible, it could be considered a documentation request 😉

I'd like to reference json serializable classes as generics. e.g. class DatabaseRepository<T extends JsonSerializable> { ... }

But when I try to use a class build with freezed package, I get the error: 'Prompt' doesn't conform to the bound 'JsonSerializable' of the type parameter 'T'. Try using a type that is or is a subclass of 'JsonSerializable'

Here's my prompt class:

import 'package:freezed_annotation/freezed_annotation.dart';

part 'prompt.freezed.dart';
part 'prompt.g.dart';

@freezed
class Prompt with _$Prompt {
  const factory Prompt({
    required String text,
    String? id,
    @Default(false) bool archived,
  }) = _Prompt;

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

My guess is that this is the right place to post this, not freezed since they use this package under the hood. But let me know if I should be posting this issue there instead.

hamishjohnson avatar Mar 23 '22 11:03 hamishjohnson

Responded on stackoverflow, regards.

t-beckmann avatar May 22 '23 21:05 t-beckmann