Home > OS >  Dart optional parameter is null type
Dart optional parameter is null type

Time:10-12

I'm trying to use optional parameter default value in my function in dart, but it causes error Error: Not a constant expression.

I tried to solve with inserting my variable to a lambda function that returns int, but it didn't worked. See my code

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 );
  }
}

is there a way to use optional int in Delay?

CodePudding user response:

Remove const on the Duration constructor. There are no issues with your use of optional parameters.

Dart cannot create a compile-time constant from a potentially variable function argument.

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