0

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?

Addow
  • 104
  • 1
  • 2
  • 7
  • just for knowing , why are you doing this way , you can covert first model to frezzed model so you can use both model in anywhere you want – Jinto Joseph Mar 21 '22 at 07:31
  • I tried to make all freezed but didnt work that way, this is final supermarket = await FirebaseFirestore.instance .collection('supermarkets') .doc(documentId) .get(); how I get the data. – Addow Mar 21 '22 at 07:48

1 Answers1

1

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(),
    );
  }
}
salihgueler
  • 3,284
  • 2
  • 22
  • 33
  • 1
    I defined the properties inside the constructor because I was using freezed before and then I refactored to not use freezed and forgot to define the fields in the class, thanks @salihgueler for noticing that. – Addow Mar 21 '22 at 08:41