颤抖 - 如何在'未来'中展示`snackbar`

问题描述 投票:0回答:1

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

register.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似乎没有这样的设施。

android ios dart flutter flutter-layout
1个回答
0
投票

像这样为你的脚手架创建一个键:

var _key = new GlobalKey<ScaffoldState>();

然后用你的脚手架附上它:

Scaffold(
    key: _key,
    body: your_ui_here,
)

将这把钥匙传递给你的未来

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

您可以将此密钥传递到任何位置,只要附加的脚手架未被丢弃,它就会起作用。

© www.soinside.com 2019 - 2024. All rights reserved.