首页 > 解决方案 > 字符串不是颤振中持续时间的子类型

问题描述

fromJson()在颤振中的方法出现错误:

  factory ReminderModel.fromJson(Map<String, dynamic> json) => ReminderModel(
        id: json["id"] == null ? null : json["id"],
        dayName: json["dayName"] == null ? null : json["dayName"],
        workStartTime: DateTime.parse(json["workStartTime"]),
        workEndTime: DateTime.parse(
          json["workEndTime"],
        ),
        singleReminderModel: json["singleReminderModel"] == null
            ? null
            : List<SingleReminderModel>.from(
                json["singleReminderModel"].map(
                  (x) => x.toString(),
                ),
              ),
        frequency: json["frequency"] == null ? null : json["frequency"],
        breakPeriod: json["isPending"] == null ? null : json["breakPeriod"],
      );

我的模型如下所示:

  int? id;
  String? dayName;
  DateTime? workStartTime;
  DateTime? workEndTime;
  List<SingleReminderModel>? singleReminderModel;
  Duration? frequency;
  Duration? breakPeriod;

  ReminderModel({
    this.id,
    this.dayName,
    this.workStartTime,
    this.workEndTime,
    this.singleReminderModel,
    this.frequency,
    this.breakPeriod,
  });

我需要准确地保存durationtostring和 back to duration

toJson()当我在我的方法中保存这样的数据时,我没有出错

"frequency": frequency!.toString(),

**更新:**建议的编辑后,我收到此错误:

在此处输入图像描述

标签: flutterdart

解决方案


尝试这样做

factory ReminderModel.fromJson(Map<String, dynamic> json) => ReminderModel(
        ...
        frequency: Duration(microseconds: json["frequency"] ?? 0),
        breakPeriod: json["isPending"] == null ? null : Duration(microseconds: json["breakPeriod"] ?? 0),
      );

转 JSON 函数

Map<String, dynamic> toJson() => {
        ...
        "frequency": frequency!.inMilliseconds,
        "breakPeriod": breakPeriod!.inMilliseconds,
      }

推荐阅读