【问题标题】:String is not a subtype of duration in flutter字符串不是颤振中持续时间的子类型
【发布时间】:2021-10-11 05:27:37
【问题描述】:

我在 Flutter 中的 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,
  });

我需要准确地将duration 保存到string 并返回到duration

当我将这样的数据保存在我的 toJson() 方法中时,我没有收到任何错误

"frequency": frequency!.toString(),

**更新:** 在建议的编辑之后,我收到了这个错误:

【问题讨论】:

  • 你需要投到Duration,可以加到Json吗?
  • 如何添加演员表?你能举个例子吗?是的,我可以添加到Json
  • 那么请添加,以便我确定答案。 json["frequency"] as Duration().
  • 完成请检查

标签: flutter dart


【解决方案1】:

输出

从字符串中解析 Duration 使用这种方法。把它放在这个类之外,

Duration parseDuration(String s) {
  int hours = 0;
  int minutes = 0;
  int micros;
  List<String> parts = s.split(':');
  if (parts.length > 2) {
    hours = int.parse(parts[parts.length - 3]);
  }
  if (parts.length > 1) {
    minutes = int.parse(parts[parts.length - 2]);
  }
  micros = (double.parse(parts[parts.length - 1]) * 1000000).round();
  return Duration(hours: hours, minutes: minutes, microseconds: micros);
}

转换喜欢

  frequency:
            json["frequency"] == null ? null : parseDuration(json["frequency"]),
        breakPeriod: json["isPending"] == null
            ? null
            : parseDuration(json["breakPeriod"]),

FullWidget+Everything

import 'package:flutter/material.dart';

class WidgetTest extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        children: [
          ElevatedButton(
              onPressed: () {
                final ReminderModel model = ReminderModel(
                  id: 1,
                  dayName: "sunDay",
                  workEndTime: DateTime.now(),
                  workStartTime: DateTime.now(),
                  frequency: Duration(seconds: 4),
                  breakPeriod: Duration(minutes: 12),
                );
                final json = model.toJson();

                print(json.toString());
                final ReminderModel m = ReminderModel.fromJson(json);

                print("id from model: ${m.id}");
              },
              child: Text("FR"))
        ],
      ),
    );
  }
}

class TableJson {
  final String value1 = "1";
}

class ReminderModel {
  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.frequency,
    this.breakPeriod,
  });

  Map<String, dynamic> toJson() => {
        "id": id,
        "dayName": dayName!,
        "workStartTime": workStartTime!.toIso8601String(),
        "workEndTime": workEndTime!.toIso8601String(),
        // "workHour": workHour!.toString(),
        // "singleRemindeModel": singleReminderModel == null
        //     ? null
        //     : List<dynamic>.from(
        //         singleReminderModel!.map(
        //           (e) => e.toJson(),
        //         ),
        //       ),
        "frequency": frequency!.toString(),
        "breakPeriod": breakPeriod!.toString(),
      };

  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"],
        ),
        frequency:
            json["frequency"] == null ? null : parseDuration(json["frequency"]),
        breakPeriod: json["isPending"] == null
            ? null
            : parseDuration(json["breakPeriod"]),
      );
}

Duration parseDuration(String s) {
  int hours = 0;
  int minutes = 0;
  int micros;
  List<String> parts = s.split(':');
  if (parts.length > 2) {
    hours = int.parse(parts[parts.length - 3]);
  }
  if (parts.length > 1) {
    minutes = int.parse(parts[parts.length - 2]);
  }
  micros = (double.parse(parts[parts.length - 1]) * 1000000).round();
  return Duration(hours: hours, minutes: minutes, microseconds: micros);
}

事情会产生任何错误吗?

参考:here

【讨论】:

  • 试过这个我得到一个Unhandled Exception: FormatException: Invalid double 错误
  • 我认为您来自SingleReminderModel。你能把那个模型也加进去吗?
  • 单个提醒模型只有一个整数和日期时间,格式正确,分别保存到 dB。它不会抛出任何错误
  • 我更新了我的答案,检查它是否对您产生任何错误?
【解决方案2】:

试试这样

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,
      }

【讨论】:

  • 没有工作仍然得到 String is not a subtype of int 错误
  • 你应该先删除旧文档,因为你已经在数据库中有一些文档包含“频率”和“breakPeriod”作为字符串而不是数字
猜你喜欢
  • 2021-09-23
  • 1970-01-01
  • 2021-08-09
  • 2020-10-28
  • 2022-12-12
  • 2021-08-22
  • 1970-01-01
  • 1970-01-01
  • 2019-01-28
相关资源
最近更新 更多