如何在Flutter中返回地图

时间:2019-03-05 10:17:14

标签: dart flutter

如何获取apiRequest方法的返回值?

此函数在外部创建

 Future<Map> apiRequest(String url, Map jsonMap) async {
      HttpClient httpClient = HttpClient();
      HttpClientRequest request = await httpClient.postUrl(Uri.parse(url));
      request.headers.set('content-type', 'application/json');
      request.add(utf8.encode(json.encode(jsonMap)));
      HttpClientResponse response = await request.close();
      print(response);
      print(request);
      // todo - you should check the response.statusCode

      String reply = await response.transform(utf8.decoder).join();
      Map valueMap = json.decode(reply);
      print(valueMap);
      httpClient.close();
      return valueMap;
    }

在主函数中,我传递了值

var value = apiRequest(url, {"username":"admin"});

但是我无法将此值传递给我的模型类

UsernameModel model = UsernameModel.fromJson(value);

1 个答案:

答案 0 :(得分:1)

您还需要async中的await / main。异步执行具有传染性,您不能从异步调用返回到非异步执行。

Future main() async {
  var value = await apiRequest(url, {"username":"admin"});
  UsernameModel model = UsernameModel.fromJson(value);
  ...
}