Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I add a custom function inside the class annotated with the 'freezed' library?

Tags:

flutter

dart

I have defined a class like this and annotated with the freezed library.

@freezed
@immutable
abstract class CommentMediaAttachmentModel with _$CommentMediaAttachmentModel {
  const factory CommentMediaAttachmentModel({
    final String type,
    final String mediaUrl,
    final int width,
    final int height
  }) = _CommentMediaAttachmentModel;

  bool isAnimated() {
    return type == 'ANIMATED';
  } 
}

I'd like to add a quick function isAnimated to determine the type variable, but on compilation, it doesn't allow me to do so:

lib/presentation/comment/model/comment_attachment_model.freezed.dart:292:7: Error: The non-abstract class '_$_CommentMediaAttachmentModel' is missing implementations for these members:
 - CommentMediaAttachmentModel.isAnimated
Try to either
 - provide an implementation,
 - inherit an implementation from a superclass or mixin,
 - mark the class as abstract, or
 - provide a 'noSuchMethod' implementation.

Upon checking the generated class _$_CommentMediaAttachmentModel, isAnimated function isn't implemented. How can I achieve that?

Edit: Below is the code of _$_CommentMediaAttachmentModel. I'm not sure why I cannot paste that snippet to SO, it just said the code is malformed. I will use a screen capture instead: enter image description here

like image 380
am5a03 Avatar asked Feb 03 '26 00:02

am5a03


1 Answers

To manually define methods/properties on the class, as stated in freezed documentation, you have to define a single private constructor:

@freezed
@immutable
abstract class CommentMediaAttachmentModel with _$CommentMediaAttachmentModel {
  const CommentMediaAttachmentModel._(); // Added constructor
  const factory CommentMediaAttachmentModel({
    final String type,
    final String mediaUrl,
    final int width,
    final int height
  }) = _CommentMediaAttachmentModel;

  bool isAnimated() {
    return type == 'ANIMATED';
  } 
}
like image 193
THelloThere Avatar answered Feb 04 '26 13:02

THelloThere



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!