如何解决使用Flutter模型时出现的DateTime异常

dw1jzc5e  于 2022-12-14  发布在  Flutter
关注(0)|答案(1)|浏览(152)

我通过API接收数据并将其存储在移动的应用程序的配置单元框中。DateTime字段引发异常。
我的原始数据来自API响应;

{"pointOfServiceNo":"3","pointOfServiceName":"DEANO POS 2","pointOfServiceDescription":"DEANO POS 2","pointOfServiceOrderingGroupNo":"113-1","orders":[{"orderType":"inventory","orderDate":"2022-12-08","deliveryDate":"2022-12-08"}

例外的是;

Exception has occurred. _TypeError (type 'String' is not a subtype of type 'DateTime?')

这是我的Model方法;

List<Orders> ordersListFromJson(String val) => List<Orders>.from(
json.decode(val)['orders'].map((val) => Orders.ordersInfofromJson(val)));

@HiveType(typeId: 2)
class Orders extends HiveObject {
@HiveField(0)
String? orderType;
@HiveField(1)
DateTime? orderDate;
@HiveField(2)
DateTime? deliveryDate;
@HiveField(3)
List<Articles>? articles;

Orders({this.orderType, this.orderDate, this.deliveryDate, this.articles});

factory Orders.ordersInfofromJson(Map<String, dynamic> orders) => Orders(
  orderType: orders['orderType'],
  orderDate: orders[DateTime.tryParse('orderDate')],
  deliveryDate: orders[DateTime.tryParse('deliveryDate')],
  articles: List<Articles>.from(orders['articles']
      .map((articles) => Articles.articlesfromJson(articles))));
 }

有没有关于我做错了什么的反馈?我是一个很新的Flutter等。任何指针将不胜感激。

uxhixvfz

uxhixvfz1#

您没有访问在json中接收到的orderDate和deliveryDate字段的数据。请尝试以下方法:

factory Orders.ordersInfofromJson(Map<String, dynamic> orders) => Orders(
orderType: orders['orderType'],
orderDate: DateTime.tryParse(orders['orderDate']),
deliveryDate: DateTime.tryParse(orders['deliveryDate']),
articles: List<Articles>.from(orders['articles']
.map((articles) => Articles.articlesfromJson(articles))));
}

相关问题