1

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?

creativecreatorormaybenot
  • 114,516
  • 58
  • 291
  • 402
Batuhan Özkan
  • 137
  • 1
  • 4
  • 13
  • There is no scenario that only allows `const` values. That is impossible in Dart, i.e. it always occurs because your code specifies it that way. If you cannot pass `oneSec` if it is not `const`, then you should share the rest of your code. – creativecreatorormaybenot Oct 02 '19 at 13:28
  • 1
    Could you talk more on what you want to do? – Tokenyet Oct 02 '19 at 13:33
  • ı want to run setState function periodically. For example, at first setState function will work in 200 ms then at second will work 300 then ... bla bla – Batuhan Özkan Oct 02 '19 at 14:57

2 Answers2

1

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);
creativecreatorormaybenot
  • 114,516
  • 58
  • 291
  • 402
  • @BatuhanÖzkan Looking at the edits to your question, *you* changed the meaning of your own question when you changed "Dart does not accept the `const` keyword" to "Dart only accept the `const` keyword". I'm not sure that you fully understand how `const` works; you do *not* and should *not* be using `const` at all since you're not using compile-time constants, and Dart will require using `const` objects only if *you* have already requested that it be in a `const` context. – jamesdlin Oct 02 '19 at 16:13
  • @jamesdlin No. At first my question was " dart doesn't accept except const variable for duration time". Then creativecreatorormaybenot changed my question as"Dart does not accept the const keyword" so the meaning was changed. Then i changed my question as"Dart only accept the const keyword" – Batuhan Özkan Oct 02 '19 at 17:01
0

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.

jamesdlin
  • 81,374
  • 13
  • 159
  • 204