首页 > 解决方案 > 将获取请求正文同步分配给变量 - 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();
   }

标签: flutterdart

解决方案


您可以使用 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();
        });

推荐阅读