I have a function that adds the string "add" to the list every 5 seconds. How can I make a function so that it randomly selects one of 3 rows and adds it? And every 5 seconds chose another. Strings: 'add', 'delete', 'remove'. My code:
class EventNotifier extends ValueNotifier<List<String>> {
EventNotifier(List<String> value) : super(value);
final stream = Stream.periodic(const Duration(seconds: 5));
late final streamSub = stream.listen((event) {
value.add('add');
});
}
CodePudding user response:
Random is indeed the way to go. Since this is Dart, and not JS, Math.random()
specifically won't work, but you can use Random
in dart:math
instead ;)
final List<String> options = ["add", "delete", "remove"];
...
value.add(options[Random().nextInt(4)]); // max of 4 to get a random index in [0, 1, 2]
Same as the other answer, it's pseudo-random, but definitely good enough