toJson not working properly json serializer Unhandled Exception: Invalid argument: Instance of 'DietModel'


I am trying to save data on firestore but getting error while saving in toJson. i have created two models diet-model and TargetModel to store on firestore using json_serializable: ^4.0.0 and json_annotation: ^4.0.0 . TargetModel have List of diet models. error is run time error


Unhandled Exception: Invalid argument: Instance of 'DietModel'
[        ] E/flutter (23502): #0      convertPlatformException (package:cloud_firestore_platform_interface/src/method_channel/utils/exception.dart:13:5)
[        ] E/flutter (23502): #1      MethodChannelDocumentReference.set (package:cloud_firestore_platform_interface/src/method_channel/method_channel_document_reference.dart:43:13)
[        ] E/flutter (23502): <asynchronous suspension>
[        ] E/flutter (23502): #2      DietPageRepositoryImpl.setTarget (package:dance/services/firestore/firestore-impl/diet-page-repository-impl.dart:31:5)
[        ] E/flutter (23502): <asynchronous suspension>
[        ] E/flutter (23502): #3      DietPageViewModel.setTargetedModel (package:dance/viewmodels/diet-page-view-model/diet-page-view-model.dart:120:5)
[        ] E/flutter (23502): <asynchronous suspension>

import 'package:dance/models/diet-model/diet-model.dart';
import 'package:json_annotation/json_annotation.dart';

part 'targeted-model.g.dart';

class TargetedModel {
  List<DietModel> targetedBreakfast;
  List<DietModel> targetedLunch;
  List<DietModel> targetedSnacks;
  List<DietModel> targetedDinner;

  TargetedModel(this.targetedBreakfast, this.targetedLunch, this.targetedSnacks,

  factory TargetedModel.fromJson(Map<String, dynamic> json) =>

  Map<String, dynamic> toJson() => _$TargetedModelToJson(this);

import 'package:json_annotation/json_annotation.dart';

part 'diet-model.g.dart';

class DietModel {
  int calories;
  String name;
  int carbs;
  int fat;
  int protein;
  bool selected;
  int quantity;
  String imageUrl;


  factory DietModel.fromJson(Map<String, dynamic> json) =>

  Map<String, dynamic> toJson() => _$DietModelToJson(this);

Future<void> setTarget(DateTime date, TargetedModel model) async {
    await _collectionReferenceTD.doc("$date").set(model.toJson()); // getting error here 


@JsonSerializable(explicitToJson: true)

This allows nested objects to be serialized

Also you might want to update your DietModel constructor:


Answered By – Nuts

Answer Checked By – Dawn Plyler (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *