atreeon / morphy

Provides a clean class definition with extra functionality including; copy with, json serializable, tostring, equals that supports inheritance and polymorphism
3 stars 3 forks source link

generateJson not compatible with const constructors #6

Open befora opened 5 months ago

befora commented 5 months ago

Example to recreate issue:

import 'package:morphy_annotation/morphy_annotation.dart';

part 'pet.g.dart';
part 'pet.morphy.dart';

@Morphy(generateJson: true)
abstract class $Pet {
  const $Pet();
  String get type;
}

I get this error:

Error: Non-constant map literal is not a constant expression.
  Map<Type, Object? Function(Never)> _fns = {}
befora commented 5 months ago

I removed these lines from the generated morphy.dart file and it solved the issue.

  // ignore: unused_field
  Map<Type, Object? Function(Never)> _fns = {};

  Map<String, dynamic> toJson_2([Map<Type, Object? Function(Never)>? fns]) {
    this._fns = fns ?? {};
    return toJson();
  }
atreeon commented 5 months ago

Thanks @befora, this is indeed a bug. It looks like the json functionality and the constant functionality don't work together. I'll fix this hopefully in a couple of weeks and batch some other changes up.

As a workaround you can either set the generate json to false @Morphy(generateJson: false) or you can make the class a non constant.

Perhaps it might be a rarity to have a constant that you serialize anyway as the constant value would be known at compile time??? I may be missing an edge case though and will fix it regardless.