How to generate pseudo-random number in dart

341

The default Random constructor does create a seedable pseudo-random number generator. The documentation indicates that the implementation could change across Dart versions, but my understanding is that that's not expected to happen and is not something that would be done lightly since it almost certainly would break existing code.

If you want a stronger consistency guarantee (or if you need a PRNG that generates the same values across languages or platforms), then you would need to use a specific PRNG implementation (e.g. such as an implementation of Mersenne Twister).

Share:
341
Julien Jm
Author by

Julien Jm

Updated on November 26, 2022

Comments

  • Julien Jm
    Julien Jm over 1 year

    I'm currently trying to pick up a random item in a list in dart. For this, I would like to generate a pseudo-random number (my seed) which will be the index where I'm gonna pick an element of my list.

    First, I would like to generate the seed from today's date as follow :

    import 'package:intl/intl.dart';
    final String datePattern = 'yyyy-MM-dd';
    final String todays_date = DateFormat(datePattern).format(DateTime.now());
    

    And find a way to convert it as an integer (pseudo-random number) to be able to pick up an item from a list using as index this integer.

    This way, for 10 users opening a flutter application for example, they will get the same element of the list everyday.

    List<String> dic = ['a','b','c','d','e','f','g','h','i','j']
    var randomItem = (dic.toList()..shuffle()).elementAt(myPseudoRandomNumber);
    

    How to get this variable 'myPseudoRandomNumber' shown above?

    • Ma Jeed
      Ma Jeed about 2 years
      why don't you use the Random class?
    • Julien Jm
      Julien Jm about 2 years
      @Ma Jeed the Random class should work with a seed as a parameter but then how do you generate this seed as integer from a date of type string
    • Richard Heap
      Richard Heap about 2 years
      So you need the Dart equivalent of C++ srand or Java Random?
  • Julien Jm
    Julien Jm about 2 years
    Because random will generate a random number (so yes I could use it but not alone). I would like to generate a random number from a seed that will give me the same result at each run if the seed is not changed. His equivalent in C++ would be : void srand(unsigned int seed) : cplusplus.com/reference/cstdlib/srand