【发布时间】:2020-07-17 19:42:36
【问题描述】:
飞镖版本:2.8.0
我得到了这个:'Future<String>' 的实例,即使我正在使用 await。
查看代码: 来自 loading.dart(这是应用启动时的第一页)
void setUpWorldTime() async {
WorldTime worldTime = await WorldTime(location: 'Berlin', flag: 'germany.png', url: 'Asia/Kolkata');
pri(worldTime.getTime());
}
@override
void initState() {
super.initState();
setUpWorldTime();
}
world_time.dart
import 'dart:convert';
import 'package:http/http.dart';
class WorldTime {
String location;
String time;
String flag;
String url;
WorldTime({this.location, this.flag, this.url});
Future<String> getTime() async {
print('called getTime()');
Response response = await get('http://worldtimeapi.org/api/timezone/$url');
Map data = jsonDecode(response.body);
String dateTime = data['datetime'];
String offSet = data['utc_offset'].toString().substring(1, 3);
DateTime now = DateTime.parse(dateTime);
now = now.add(Duration(hours: int.parse(offSet)));
time = now.toString();
return Future.value(time);
}
}
现在,我正在关注这个:https://www.youtube.com/watch?v=9lCQhwo8WT4&list=PL4cUxeGkcC9jLYyp2Aoh6hcWuxFDX6PBJ&index=28
在上面的教程中它正在工作,因为那时 dart 1.0 是新的
我的代码中的问题是这条语句 pri(worldTime.getTime()); 在完成 API 之前立即执行!
另外,请教我如何获得价值,我试图这样返回:return Future.value(time);
【问题讨论】:
标签: flutter dart async-await