我正在使用转换包来执行以下任务:
factory Brick.fromJson(Map<String, dynamic> json) {
return Brick(
title: json['title'],
expectedDuration: json['expected_duration'],
);
}
Future<Brick> createBrick(
String title, Duration expDur) async {
var url = 'https://api.com/bricks/';
final response = await http.post(
url,
headers: <String, String>{
"Content-Type": "application/json; charset=UTF-8",
},
body: convert.jsonEncode(<String, dynamic>{
"title": "$title",
"expected_duration": expDur,
}),
);
if (response.statusCode == 201) {
Brick newBrick = Brick.fromJson(convert.jsonDecode(response.body));
notifyListeners();
return newBrick;
} else {
throw Exception(
'${response.statusCode} ${response.reasonPhrase}');
}
}
Run Code Online (Sandbox Code Playgroud)
当我调用 createBrick 函数时,出现以下错误:
未处理的异常:将对象转换为可编码对象失败:“持续时间”实例
我应该如何转换持续时间?Duration 类文档中没有提及它。
谢谢。
您可以输入 JSON 秒(或毫秒,取决于您的功能)Duration
:
'expected_duration': expDur.inSeconds,
Run Code Online (Sandbox Code Playgroud)
并expected_duration
以秒为单位工作:
expectedDuration: Duration(seconds: json['excepted_duration']),
Run Code Online (Sandbox Code Playgroud)
如果持续时间少于一秒(毫秒),则应使用毫秒而不是秒。
归档时间: |
|
查看次数: |
1267 次 |
最近记录: |