flutterdartclean-architecture

Flutter/Dart: Subclass a freezed data class


I am using the following plugin: https://pub.dev/packages/freezed

I want to subclass a freezed data class to provide additional functionality in my data layer. So I have my data class which looks like:

import 'dart:ui';
import 'package:freezed_annotation/freezed_annotation.dart';
part 'card.freezed.dart';

@freezed
abstract class Card with _$Card {
  factory Card({String text, Color color, List<String> categories}) = _Card;
}

Now I want to have this Card class as a super class to my CardModel so that the CardModel has access to the same fields, the copyWith method, value equality, ... But I have no Idea how to go about this. I am trying something like this:

import 'package:flutter/widgets.dart';
import 'package:growthdeck/features/card_deck/domain/entities/card.dart';

import '../../domain/entities/card.dart';

abstract class CardModel extends Card {
  factory CardModel.fromMap(Map<String, dynamic> card) => Card(
        text: card["text"],
        color: Color(int.parse(card['color'])),
        categories: card['categories'] as List<String>,
      );
}

Which throws the following error:

package:growthdeck/features/card_deck/data/models/card_model.dart 11:9  new CardModel.fromMap
test/features/card_deck/data/models/card_model_test.dart 13:23          main.<fn>

type '_$_Card' is not a subtype of type 'CardModel' in type cast

Is there any way to do this properly? My workaround would be to simply "wrap" the Card class inside the CardModel and provide a toCard() method which is not very elegant :S


Solution

  • Freezed doesn’t support inheritance at the moment so it’s recommended to use composition instead of inheritance as mentioned by the creator here:

    https://github.com/rrousselGit/freezed/issues/464

    And in the comments of the post.