首页 > 解决方案 > 通过单击按钮在 Flutter 中停止 while 循环

问题描述

如何通过按下按钮来停止 while 循环。

 while (thirdDigit <= 9 && stopLoop == false) {
  while (sixDigits <= 999999 && stopLoop == false) {
    perspective = prefix + thirdDigit.toString() + sixDigits.toString();
    url = perspective + urlSuffix;

    validateUrl(url, numberListTiles, perspective);
    print('BotStore: $url');
    sixDigits++;
  }
  thirdDigit++;
}

}

我希望在单击按钮并分配 stopLoop = true 时停止此循环。

但是无论我按下停止按钮多少次,循环都在主线程中运行,并且按钮不会停止循环。

如何在后台运行循环并且仍然有一个正常运行的应用程序?

标签: flutterdartwhile-loop

解决方案


要在后台运行循环,请将其放入异步函数中:

Future<void> loop() async {
    // Loop here
}

要在点击按钮时停止它,请在 setState() 中将 stopLoop 设置为 true:

onPressed: () => setState(() => stopLoop = true);

推荐阅读