How to mix normal model with @freezed model?

491 Views Asked by At

I want to create CategoryModel which has two fields categoryName and items, categoryName is a String field but items are List<CategoryItem> items and CategoryItem depends on freezed code generation while CategoryModel is not.

the following is my models:

import 'package:freezed_annotation/freezed_annotation.dart';
part 'category_model.freezed.dart';
part 'category_model.g.dart';

class CategoryModel {
  const CategoryModel({
    required String categoryName,
    required List<CategoryItem> items,
  });
  factory CategoryModel.fromJson(
      List<Map<String, dynamic>> list, String categoryName) {
    return CategoryModel(
      categoryName: categoryName,
      items: list.map((json) => CategoryItem.fromJson(json)).toList(),
    );
  }
}

@freezed
class CategoryItem with _$CategoryItem {
  const factory CategoryItem({
    required String description,
    required int price,
    @JsonKey(name: 'img_url') required String imgUrl,
  }) = _CategoryItem;
  factory CategoryItem.fromJson(Map<String, dynamic> json) =>
      _$CategoryItemFromJson(json);
}

now when using I did like this:

final categories = supermarketCategories.entries.map((e) {
      return CategoryModel.fromJson(
        List<Map<String, dynamic>>.from(e.value),
        e.key,
      );
    }).toList();

and in ui I want to access like this:

data.item2.first.categoryName

and

data.item2.first.items

but I got an error saying:

The getter 'categoryName' isn't defined for the type 'CategoryModel'. Try importing the library that defines 'categoryName', correcting the name to the name of an existing getter, or defining a getter or field named 'categoryName'.

what am I doing wrong?

1

There are 1 best solutions below

1
On

Well, right now you are trying to create your CategoryModel without a system or a property to access data.

Can you try changing CategoryModel to below and try again?

class CategoryModel {
  const CategoryModel({
    required this.categoryName,
    required this.items,
  });
  final String categoryName;
  final List<CategoryItem> items;
  factory CategoryModel.fromJson(
      List<Map<String, dynamic>> list, String categoryName) {
    return CategoryModel(
      categoryName: categoryName,
      items: list.map((json) => CategoryItem.fromJson(json)).toList(),
    );
  }
}