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

Issue

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

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';

@JsonSerializable()
class TargetedModel {
  List<DietModel> targetedBreakfast;
  List<DietModel> targetedLunch;
  List<DietModel> targetedSnacks;
  List<DietModel> targetedDinner;

  TargetedModel(this.targetedBreakfast, this.targetedLunch, this.targetedSnacks,
      this.targetedDinner);

  factory TargetedModel.fromJson(Map<String, dynamic> json) =>
      _$TargetedModelFromJson(json);

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

import 'package:json_annotation/json_annotation.dart';

part 'diet-model.g.dart';

@JsonSerializable()
class DietModel {
  int calories;
  String name;
  int carbs;
  int fat;
  int protein;
  bool selected;
  int quantity;
  String imageUrl;

  DietModel();

  factory DietModel.fromJson(Map<String, dynamic> json) =>
      _$DietModelFromJson(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 
  }

Solution

Add
@JsonSerializable(explicitToJson: true)

This allows nested objects to be serialized

Also you might want to update your DietModel constructor:

  DietModel({this.calories, this.name...

Answered By – Nuts

Answer Checked By – Dawn Plyler (FlutterFixes Volunteer)

Leave a Reply

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