I'm receiving data via an API and storing it in a Hive box within my mobile application. An exception is being thrown on a DateTime field.
My raw data from the API response;
{"pointOfServiceNo":"3","pointOfServiceName":"DEANO POS 2","pointOfServiceDescription":"DEANO POS 2","pointOfServiceOrderingGroupNo":"113-1","orders":[{"orderType":"inventory","orderDate":"2022-12-08","deliveryDate":"2022-12-08"}
The exception is;
Exception has occurred. _TypeError (type 'String' is not a subtype of type 'DateTime?')
This is my Model method;
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))));
}
Any feedback on what i'm doing wrong? I'm pretty new to Flutter etc. Any pointers would be greatly appreciated.
CodePudding user response:
You are not accessing the data received in your json for the fields orderDate and deliveryDate. Try this way:
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))));
}