警报对话框无限运行

时间:2021-03-03 09:10:38

标签: flutter dart async-await

您好,我正在尝试运行以下代码,我想运行特定的异步代码并显示警报对话框,直到它运行为止。但是代码在 await showAlertDialog(); 这一行之后没有被执行。

  void appendAndRunPythonCode() async {
    await showAlertDialog();
    await runPythonScript(final_code);
    _alertDialogUtils.dismissAlertDialog(context);
  }

这是我的 showAlertDialog() 函数的实现方式:

Future<void> showAlertDialog() async {
    if (!_alertDialogUtils.isShowing) {
      await _alertDialogUtils.showAlertDialog(context);
    }
  }

runPythonCode():

Future<void> runPythonScript(String code) async {
    if (inputImg == null) {
      ToastUtils.showToastMessage(text: ConstUtils.input_image_empty_notice);
      return;
    }

    if (code.isEmpty) {
      ToastUtils.showToastMessage(text: ConstUtils.code_empty);
      return;
    }

    List<String> lines = code.split('\n');
    String lastLine = lines.elementAt(lines.length - 4);

    if (lastLine.split(' ').elementAt(0).compareTo('outputImage') != 0) {
      ToastUtils.showToastMessage(text: ConstUtils.cv_error_line2);
      return;
    }

    data.putIfAbsent("code", () => code);
    data.putIfAbsent("inputImg", () => inputImg);
    _alertDialogUtils.showAlertDialog(context);

    final result = await _channel.invokeMethod("runPythonCVScript", data);
    //  Add Artifical Delay of 3 seconds..
    await Future.delayed(
      Duration(seconds: 3),
    );
    _alertDialogUtils.dismissAlertDialog(context);

    setState(
      () {
        _scrollController.animateTo(
          _scrollController.position.maxScrollExtent,
          curve: Curves.easeOut,
          duration: const Duration(milliseconds: 300),
        );
        output = result['textOutput'] ??= "";
        error = result['error'] ??= "";
        outputImg = (result['graphOutput']);
        data.clear();
      },
    );
  }

1 个答案:

答案 0 :(得分:1)

您不应该await showAlertDialog 因为 runPythonScript 在对话框关闭之前不会被执行。

删除 await。 像这样:

 void appendAndRunPythonCode() async {
    showAlertDialog();
    await runPythonScript(final_code);
    _alertDialogUtils.dismissAlertDialog(context);
  }
相关问题