Batuhan Özkan
Batuhan Özkan

Reputation: 147

How do I specify dynamic Duration times?

I want to dynamically increase duration time, but Dart only accepts the const keyword:

int ms=level*100+200;
const oneSec = const Duration(milliseconds: ms);

How can I solve this problem?

Upvotes: 1

Views: 318

Answers (2)

jamesdlin
jamesdlin

Reputation: 90005

Duration objects are immutable. You cannot change a Duration after it's been constructed. If you want to use increasing durations, you'll need to create a new one each time. For example:

void repeatedSetStateWithDelay(int level) {
  setState(() {
    int ms = level * 100 + 200;
    Future.delayed(
      Duration(milliseconds: ms),
      () => repeatedSetStateWithDelay(level + 1),
    );
  });
}

I'm not sure what const has to do with your question; you should not be using const in this case.

Upvotes: 0

creativecreatorormaybenot
creativecreatorormaybenot

Reputation: 126734

If you want to understand how const works, you can refer to this question.


In your case, you cannot use a const Duration because the dynamic value cannot be determined at compile time. This means that you will have to remove const and e.g. use final:

int ms = level * 100 + 200;
final oneSec = Duration(milliseconds: ms);

Upvotes: 1

Related Questions