相关疑难解决方法(0)

Dart语言支持异步/等待编程风格,还是类似?

可以用Dart语言编写类似的代码吗?

int i;
try {
  i = await getResultAsync();
} catch(exception) {
  // Do something
}
Run Code Online (Sandbox Code Playgroud)

dart dart-async

8
推荐指数
1
解决办法
951
查看次数

有没有办法同步运行Dart的未来?

如何立即获得Future的结果?例如:

void main() {
  Process.run('some_shell_command', []).then((ProcessResult result) {
    print(result.stdout); // I have the output here...
  });
  // ... but want it here.
}
Run Code Online (Sandbox Code Playgroud)

dart

7
推荐指数
2
解决办法
1504
查看次数

我可以让 Dart 函数“等待”一段时间或输入吗?

我正在尝试在 Dart 中制作一个简单的 RPG。我需要在 div 的屏幕上显示文本,并且我需要让程序在显示下一段文本之前等待用户输入。

例如:

void main() {
  showText("Hello, Adventurer! Welcome to the land of Dartia! (Press ENTER to continue...)");
  print("showText has finished");
}
Run Code Online (Sandbox Code Playgroud)

"showText has finished"在显示文本并且玩家按下回车键之前不应显示。这是我到目前为止的(在我看来很丑陋)代码:

void showText(String text) {
    var textBox = querySelector("#sample_text_id")
        ..text = "";
    var timer;
    var out;
    out = ([int i = 0]) {
        textBox.text += text[i];
        if (i < text.length - 1) timer = new Timer(const Duration(milliseconds: 10), () => out(i + 1));
    };
    out();
}
Run Code Online (Sandbox Code Playgroud)

Timerout()异步运行该函数,我不希望它这样做。理想情况下,我想写这样的东西:

void showText(String …
Run Code Online (Sandbox Code Playgroud)

html wait dart

4
推荐指数
1
解决办法
3736
查看次数

Future execution leads to unhandled exception

import 'dart:async';

void main() {
  divide(1, 0).then((result) => print('1 / 0 = $result'))
    .catchError((error) => print('Error occured during division: $error'));
}

Future<double> divide(int a, b) {
  if (b == 0) {
    throw new Exception('Division by zero');
  }
  return new Future.value(a/b);
}
Run Code Online (Sandbox Code Playgroud)

目前我正在学习如何在 Dart 中使用 future,并且我陷入了这样一个简单的例子中。当用户尝试执行除以零时,我的未来会抛出异常。但是, .catchError 不处理我的异常。我得到了未处理的异常,并带有堆栈跟踪。我很确定我错过了一些明显的东西,但无法理解到底是什么。

据我了解,还有另一种方法来处理错误:

divide(1, 0).then((result) => print('1 / 0 = $result'),
    onError: (error) => print('Error occured during division: $error'));
Run Code Online (Sandbox Code Playgroud)

使用命名可选参数 - onError。这样做仍然会导致未处理的异常。

我还想澄清一件事。我对吗?- 这两种方法之间的唯一区别是 .catchError() 还处理内部 future 抛出的错误(在外部 future 的 then() 方法内部调用的 future),而 onError …

future unhandled-exception dart

3
推荐指数
1
解决办法
2933
查看次数

标签 统计

dart ×4

dart-async ×1

future ×1

html ×1

unhandled-exception ×1

wait ×1