gpt4 book ai didi

android - Flutter - 如何在 `snackbar` 中显示 `Future`

转载 作者:行者123 更新时间:2023-11-29 05:52:21 31 4
gpt4 key购买 nike

在我的 flutter 应用程序中,我将数据从移动设备发送到服务器。该部分的完成方式如下。

注册.dart

void _createUser()
{
DataFetch().createUser(AppNavigation.getAPIUrl() +
"user/saveUser", user).then((String result){
print("RESULT IS: "+result);
});
}

data_fetch.dart

Future<String> createUser(String url, User body) async {
print("BODY: " + body.toJson().toString());

return http.post(url, body: convert.json.encode(body.toJson()), headers: {
"Accept": "application/json",
"content-type": "application/json"
}).then((http.Response response) {
final int statusCode = response.statusCode;

print("RESPONSE: " + response.body);
print("STATUS CODE: " + statusCode.toString());

if (statusCode < 200 || statusCode > 400 || response.body == null) {
throw new Exception("Error while fetching data");
} else {
return response.body;
}
});
}

我的 UI 位于 register.dart 中,data_fetch.dart 是一个单独的类,其中包含支持各种数据传递工作的方法。

我需要显示一个snackbar,直到数据保存完成。我知道我可以使用 FutureBuilder ,但无需将其附加为返回一些 UI 的小部件,因为保存数据后我没有可显示的 UI。我正在尝试将数据发送到服务器,我只需要指出这一点。

我该怎么做?无论如何,Future 中似乎没有这样的设施。

最佳答案

为你的脚手架创建一个 key ,如下所示:

var _key = new GlobalKey<ScaffoldState>();

然后将其与脚手架连接:

Scaffold(
key: _key,
body: your_ui_here,
)

将这把 key 传递给你的 future

void _createUser(var key)
{
DataFetch().createUser(AppNavigation.getAPIUrl() +
"user/saveUser", user).then((String result){
key.currentState.showSnackbar(
Snackbar(content:Text("hello"))
);
});
}

您可以将此 key 传递到任何地方,只要附加的脚手架没有被丢弃,它就会起作用。

关于android - Flutter - 如何在 `snackbar` 中显示 `Future`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55547394/

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