【问题标题】:How to wait for action of user in Flutter?如何在 Flutter 中等待用户的操作?
【发布时间】:2022-01-11 12:09:01
【问题描述】:

我的函数有问题。我需要实现一个功能,当用户点击按钮时它可以正常工作。我需要冻结这个函数并等待用户的操作。 (点击按钮)。 也许你已经面临同样的问题了

  void submitAnswer(String submittedAnswer) async {
    timerAnimationController.stop();
    if (!context.read<QuestionsCubit>().questions()[currentQuestionIndex].attempted) {
      context.read<QuestionsCubit>().updateQuestionWithAnswerAndLifeline(context.read<QuestionsCubit>().questions()[currentQuestionIndex].id, submittedAnswer);
      updateTotalSecondsToCompleteQuiz();
      //change question
      await Future.delayed(Duration(seconds: inBetweenQuestionTimeInSeconds));
      if (currentQuestionIndex != (context.read<QuestionsCubit>().questions().length - 1)) {
        updateSubmittedAnswerForBookmark(context.read<QuestionsCubit>().questions()[currentQuestionIndex]);
        timerAnimationController.stop();

        //I want to froze this part and wait for user's action.
        //When user taps on 'next', it continues working.
        //////////////////////////////////////////////////////
        changeQuestion();
        if (widget.quizType == QuizTypes.audioQuestions) {
          timerAnimationController.value = 0.0;
          showOptionAnimationController.forward();
        } else {
          timerAnimationController.forward(from: 0.0);
        }
        //////////////////////////////////////////////////////
      } else {
        updateSubmittedAnswerForBookmark(context.read<QuestionsCubit>().questions()[currentQuestionIndex]);
        navigateToResultScreen();
      }
    }
  }

当用户点击按钮时,此功能继续工作

TextButton(
        child: Text("Next >>"),
          onPressed: () {
            setState(() {
              callMyFun();
            });
            //global.setMyStatus == true;
          }
      )

【问题讨论】:

标签: flutter dart


【解决方案1】:

免责声明:虽然这可以解决您的问题,但距离 好的做法,你应该把你的功能分成两个 不一样的

您可以使用Completer 实现这一目标

例子:

Completer<void>? nextButtonCompleter;

Future<void> submitAnswer(String submittedAnswer) async {
  // Your code (removed to make answer short)
  // ...
  //I want to froze this part and wait for user's action.
  //When user taps on 'next', it continues working.

  final completer = new Completer<void>();
  nextButtonCompleter = completer;
  // This line will wait until onPressed called
  await completer.future; 
  
  // your other code
}

在你的按钮中

TextButton(
  child: Text("Next >>"),
  onPressed: () {
    setState(() {
      callMyFun();
    });
    nextButtonCompleter?.complete();
    nextButtonCompleter = null;
  }
)

【讨论】:

  • 谢谢!但它不起作用。我的功能仍然继续工作
  • @SaturnPro 也许你把我的台词放错地方了?请大神指点,我去看看
  • @Dima Rostopira 对不起,我错了。你的方法对我有帮助,谢谢! =)
猜你喜欢
  • 1970-01-01
  • 2012-01-03
  • 1970-01-01
  • 2021-04-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-16
相关资源
最近更新 更多