Dart:我如何只在程序等待来自函数的值时运行while循环?

4uqofj5v  于 2023-05-20  发布在  其他
关注(0)|答案(3)|浏览(101)
void main() async {
  print("Function Starting");
  // I want a while loop here and break once the function has completed.
  print(await myFunction());
}

Future<String> myFunction() {
  return Future.delayed(Duration(seconds: 5), () => "Function completed");
}

我基本上想有程序 Flink “联系服务器”,而其等待功能完成。
谢谢大家:)

b1zrtrql

b1zrtrql1#

这将是未来建造者的标准用法。只要在使用CircularProgressIndicator的几十个例子中选择一个,然后在那里放一个 Flink 的消息。

f5emj3cl

f5emj3cl2#

图形化UI的最明显的解决方案是Flutter和FutureBuilder。
但是如果你想在控制台中使用普通的Dart:

import 'dart:async';

void main() async {
  print("Function Starting");
  
  final blinkWhileWaiting = Timer.periodic(const Duration(seconds: 1), (timer) => print("blink"));
  
  final result = await myFunction();
  
  blinkWhileWaiting.cancel();
  
  // I want a while loop here and break once the function has completed.
  print(result);
}

Future<String> myFunction() {
  return Future.delayed(Duration(seconds: 5), () => "Function completed");
}
jv2fixgn

jv2fixgn3#

void main() async {
  bool hasFinished = false;
  Timer.periodic(const Duration(milliseconds: 500), (timer) {
    if (hasFinished == true) {
      timer.cancel();
    } else {
      print("Please wait, we are contacting the server...\n");
    }
  });
  hasFinished = await myFunction();
  print("Connected to server");
}

Future<bool> myFunction() {
  return Future.delayed(Duration(seconds: 5), () => true);
}

谢谢你julemand101这正是我要找的。我设法让它工作。

相关问题