skip to Main Content

I want to build a Flutter app with a counter, just like the same as that in the given sample:
enter image description here
Whenever it starts it must give different results and stops randomly. I’ve built the counter but failing to make it stop randomly in Flutter.

2

Answers


  1. If you can define the random value when the animation starts, I guess you could simply use something like:

    var randomValue = Random().nextDouble() * yourMaxValue;
    

    which will return a random double between 0.0 and 1.0 that you can multiply by your max range to get a randomly generated value between 0 (yourMaxValue * 0.0) and yourMaxValue (yourMaxValue * 1.0), then stop the animation when that value is reached.

    If you want to define it on the fly, you could, on each step of your animation, call something like:

    if (maxValueReached || Random().nextBoolean()) {
       stopAnimation();
    }
    

    But I guess it will mostly often stop the animation very soon. Probably would I go for something that has lowest chance to break earlier, and has its chance factor increasing as it goes higher, but I don’t know what topic we’re talking about here.

    Login or Signup to reply.
  2. That’s How You can Done it Buddy !

    void _startCounter() {
        _counter = _random.nextInt(100);
        _timer?.cancel();
        _timer = Timer.periodic(Duration(milliseconds: 100), (timer) {
          setState(() {
            _counter++;
          });
    
          if (_random.nextInt(100) < 5) {
            _timer?.cancel();
          }
        });
      }
    

    if you are using something like stream every thing will be same
    just Don’t Forget to Replace 100 by Your Max value

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search