gpt4 book ai didi

flutter - 如何在 flutter 中调用 API?

转载 作者:行者123 更新时间:2023-12-02 00:09:02 26 4
gpt4 key购买 nike

在我的 flutter 应用程序中,我想调用两个 API。例如 API A 和 API B。如果 API A 加载数据,则调用 API B 并在 listView 中显示 API B 数据。如何将 API A 数据作为参数传递给 API B?

API A 成功加载数据并在下拉列表中显示后,调用 API B。这是我的代码:

Widget build(BuildContext context) {

body: new SafeArea(

child: new Form(

child: new ListView(

children: <Widget>[
FutureBuilder('API A data'),
Container(
FutureBuilder('API B data'),
)]))

最佳答案

您可能想要创建 Controller (只是一个包含重要功能/业务逻辑的类 - 主要用于数据操作)以便于维护。

例。

class LoginController {
static Future<http.Response> login(
{@required String email, @required String password}) async {
var params = {
'email': email,
'password': password,
};

var response = await http.post(ApiRoute.LOGIN,
body: json.encode(params));

/// If the first API call is successful
if (response.statusCode == HttpStatus.ok) {
var secondResponse = SecondController.anothrFunction();

/// Do something related to the response of second api call here
}

/// Do other stuffs here

return response;
}
}

class SecondController {
static Future<http.Response> anotherFunction(
{@required String something}) async {
var params = {
'something': something,
};

var response = await http.post(ApiRoute.SOMETHING,
body: json.encode(params));
return response;
}
}

然后您可以调用 LoginController.login,这将调用两个 API。

关于flutter - 如何在 flutter 中调用 API?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59662548/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com