flutter - 将获取请求正文同步分配给变量 - Dart
问题描述
我有一个使用 get 请求的 Future 函数,并将请求正文保存到变量 { data } 中。它运行良好,但是当我运行我的应用程序并尝试使用数据加载页面时,变量在被赋值之前被访问。只有在我热重载后它才会显示。
如何让整个页面等到分配变量?
static Future<Ticket> futureTicket;
Map<String, dynamic> data;
Future<Ticket> fetchTicket() async {
final response =
await http.get('http://hostname/getRequest');
if (response.statusCode == 200) {
// If the server did return a 200 OK response, then parse the JSON.
this.data = json.decode(response.body);
//print("Data Here: " + data.toString());
return Ticket.fromJson(json.decode(response.body));
} else {
// If the server did not return a 200 OK response, then throw an exception.
throw Exception('Failed to load Ticket');
}
}
@override
void initState(){
futureTicket = fetchTicket();
super.initState();
}
解决方案
您可以使用 FutureBuilder 小部件,它需要一个未来数学
Future<Ticket> fetchTicket() async {
final response =
await http.get('http://hostname/getRequest');
if (response.statusCode == 200) {
// If the server did return a 200 OK response, then parse the JSON.
this.data = json.decode(response.body);
//print("Data Here: " + data.toString());
return Ticket.fromJson(json.decode(response.body));
} else {
// If the server did not return a 200 OK response, then throw an exception.
throw Exception('Failed to load Ticket');
}
}
FutureBuilder(
future: fetchTicket()(),
builder: (BuildContext context, snapshot) {
if (snapshot.hasData) {
// this means the fetching is completed
var data = snapshot.data;
/// you can do what ever you like with [data] variable
return YourWidget();
} else if (snapshot.hasError) {
// this means incomplete get Request
return YourErrorWidget()
}
return CircularProgressIndicator();
});
推荐阅读
- vue.js - 使用 BootstrapVue 以编程方式编写导航链接的正确方法
- c# - Windows 用于证书吊销(OCSP 或 CRL)的算法是什么以及如何配置它们?
- forms - VueJs 中动态表单的验证
- javascript - 柴在浅层平等断言上失败了
- c++ - 如何通过指针访问数组的元素?
- prolog - 使用 clpfd 的问题空间很小,超出了 SWI-Prolog 堆栈限制
- scala - 更简洁地从 spark 数据框中选择多列
- typescript - strictNullChecks 导致错误:泛型类型不存在 hasOwnProperty
- mongodb - 动态访问MongoDB字段
- android - Android:在我的应用程序中实现 Trusted Place API