Lal*_*wat 2 jsonserializer dart flutter
我正在尝试将数据保存在 firestore 上,但在保存到 toJson 时出现错误。我创建了两个模型 Diet-model 和 TargetModel 使用 json_serialized: ^4.0.0 和 json_annotation: ^4.0.0 存储在 firestore 上。TargetModel 有饮食模型列表。错误是运行时错误
错误:
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>
Run Code Online (Sandbox Code Playgroud)
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);
}
Run Code Online (Sandbox Code Playgroud)
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);
}
Run Code Online (Sandbox Code Playgroud)
Future<void> setTarget(DateTime date, TargetedModel model) async {
await _collectionReferenceTD.doc("$date").set(model.toJson()); // getting error here
}
Run Code Online (Sandbox Code Playgroud)
添加
@JsonSerializable(explicitToJson: true)
这允许嵌套对象被序列化
另外,您可能想更新 DietModel 构造函数:
DietModel({this.calories, this.name...
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
536 次 |
| 最近记录: |