Dart 可选参数为 null 类型

Dart optional parameter is null type

我试图在我的 dart 函数中使用可选参数默认值,但它会导致错误 Error: Not a constant expression.

我试图通过将我的变量插入 returns int 的 lambda 函数来解决这个问题,但它没有用。查看我的代码

Stream<int> testAsync(int n, {int delay = 100}) async* {
  if (n > 0) {
    await Future.delayed(const Duration(microseconds: delay));
    yield n;
    yield* testAsync( n-1 );
  }
}

有没有办法在Delay中使用optional int?

删除 Duration 构造函数上的 const。您使用可选参数没有问题。

Dart 无法从潜在变量函数参数创建编译时常量。

Stream<int> testAsync(int n, {int delay = 100}) async* {
  if (n > 0) {
    await Future.delayed(Duration(microseconds: delay));
    yield n;
    yield* testAsync( n-1 );
  }
}