【问题标题】:How to use two functions to wait for user input to continue async script?如何使用两个函数等待用户输入继续异步脚本?
【发布时间】:2023-02-23 12:20:05
【问题描述】:

在以下链接中:

https://stackoverflow.com/a/70667161/17826267

@SaturnPro 问了一个很好的问题,@Dmytro Rostopira 使用 Completer 作为相对简单的解决方案得到了很好的答案,但我对部分答案感到困惑:

“免责声明:虽然这会解决你的问题,但它远非良好实践,你应该将你的功能分成两个不同的功能”

如何使用两个函数来解决@SaturnPro 面临的问题?

【问题讨论】:

    标签: dart async-await


    【解决方案1】:

    要将代码拆分为两个方法,您可以将处理用户回答的逻辑和等待按下“下一步”按钮的逻辑拆分为两个单独的方法。

    这是一个例子:

    Completer<void>? nextButtonCompleter;
    
    Future<void> processAnswer(String submittedAnswer) async {
      // Your code for processing the answer here
      // ...
    
      // Wait for "Next" button to be pressed
      await waitForNextButton();
      
      // Continue with other code
    }
    
    Future<void> waitForNextButton() async {
      final completer = Completer<void>();
    
      nextButtonCompleter = completer;
      await completer.future;
    
      nextButtonCompleter = null;
    }
    
    void onNextButtonPressed() {
      setState(() => callMyFun());
    
      nextButtonCompleter?.complete();
    }
    
    // In your button widget
    TextButton(
      child: Text("Next >>"),
      onPressed: onNextButtonPressed,
    )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-03-08
      • 1970-01-01
      • 2018-12-24
      • 2020-11-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多