I created two model classes with freezed. One class is having parameter of other class inside it. The problem started when I try to send data to firestore. This following error appears.
E/flutter ( 6175): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: Invalid argument: Instance of '_$_Category'
E/flutter ( 6175): #0 convertPlatformException
package:cloud_firestore_platform_interface/…/utils/exception.dart:14
E/flutter ( 6175): #1 MethodChannelDocumentReference.set
package:cloud_firestore_platform_interface/…/method_channel/method_channel_document_reference.dart:44
E/flutter ( 6175): <asynchronous suspension>
E/flutter ( 6175): #2 _JsonCollectionReference.add
package:cloud_firestore/src/collection_reference.dart:109
E/flutter ( 6175): <asynchronous suspension>
E/flutter ( 6175): #3 _WithConverterCollectionReference.add
package:cloud_firestore/src/collection_reference.dart:180
E/flutter ( 6175): <asynchronous suspension>
E/flutter ( 6175): #4 _HomeScreenState.product
package:mr_grocery/home/home_screen.dart:45
E/flutter ( 6175): <asynchronous suspension>
Model classes
- Product (which has parameter of Category class)
@freezed
class Product with _$Product {
const factory Product({
required int amount,
required List<Category> categories, // Category class generated by freezed
required String description,
required List<String> images,
required bool inStock,
required String name,
required String quantity,
dynamic soldQuantity,
dynamic createdAt,
dynamic updatedAt,
bool? exclusive,
}) = _Product;
factory Product.fromJson(Map<String, dynamic> json) =>
_$ProductFromJson(json);
}
- Category
@freezed
class Category with _$Category {
const factory Category({
required String image,
required String name,
// @_ColorSerlizeable() required Color? color,
}) = _Category;
factory Category.fromJson(Map<String, dynamic> json) =>
_$CategoryFromJson(json);
}
Using withConverter
from Firestore package
CollectionReference<Product> products() {
const path = FirebasePaths.products;
return _firestore.collection(path).withConverter<Product>(
fromFirestore: (snapshot, options) => Product.fromJson(
snapshot.data() ?? const {},
),
toFirestore: (value, options) => value.toJson(),
);
}
build.yaml
targets:
$default:
builders:
json_serializable:
options:
# Options configure how source code is generated for every
# `@JsonSerializable`-annotated class in the package.
#
# The default value for each is listed.
any_map: false
checked: false
constructor: ""
create_factory: true
create_to_json: true
disallow_unrecognized_keys: false
explicit_to_json: true // -- Specified to true
field_rename: none
generic_argument_factories: false
ignore_unannotated: false
include_if_null: true
part 'product.g.dart';
file – Allonge