首页 > 解决方案 > 如何强制关闭 GetX Snackbar?

问题描述

Get.snackbar()用来展示连接到 API 的过程。我不明白如何以编程方式关闭小吃店?我有以下代码:

@override
  Future<List> getImportantData(String inputData) async {
    try {
      final token =  basicApiAuthString;
      print("requesting API with the following request: $inputData");
      Get.snackbar(
          "Requesting very important data...",
          "",
          duration: 60.seconds, // it could be any reasonable time, but I set it lo-o-ong
          snackPosition: SnackPosition.BOTTOM,
          showProgressIndicator: true,
          isDismissible: true,
          backgroundColor: Colors.lightGreen,
          colorText: Colors.white,
        );
      List importantData = await _client.requestAPI(basicAuthString: token, body: inputData);
          .then((importantData) {
              // Here I need to dismiss the snackbar I am still showing to user
              print("I want to close snackbar here but I don't know how to do that!");
              // Then I return data for future processing... 
              return importantData;
                });

      return importantData;
    } on DioError catch (error) {
      // Here I handle all possible API errors... Also I want to close snackbar here as well.
  
    }
 } // getImportantData() function.

我需要考虑以下几点:

  1. 应用程序可能会在请求期间关闭并再次打开(因此小吃店可能会关闭,但我可以通过状态回调知道它(未显示)
  2. 用户在请求期间可能会关闭小吃店
  3. 请求可能在毫秒内完成
  4. 可能存在 API 错误,.then()部分将永远不会被执行。

所以,我需要一些外部方法来关闭零食。Navigator.of(context).hide...不是我使用 GetX 的解决方案。

———— PS:这里是snackbar的定义,帮我澄清一下:

https://pub.dev/documentation/get/3.4.2/route_manager/GetNavigation/snackbar.html

标签: androidflutterdartflutter-getxsnackbar

解决方案


GetX 已经有一个名为closeAllSnackbars()and的方法closeCurrentSnackbar()

所以closeAllSnackbars()用来关闭所有打开的 Snackbars。

Get.closeAllSnackbars();

要关闭当前活动的 snakbar,只需调用closeCurrentSnackbar().

Get.closeCurrentSnackbar();

您还可以通过调用来查看小吃店是否打开/活动的天气isSnackbarOpen()

Get.isSnackbarOpen();

推荐阅读