如何创建一个随机选择字符串的函数?

How to create a function that randomly selects a string?

我有一个函数,每 5 秒将字符串“add”添加到列表中。我如何制作一个函数,以便它随机选择 3 行之一并添加它?每 5 秒选择另一个。 字符串:'add'、'delete'、'remove'。 我的代码:

    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');
      });
    }

随机确实是要走的路。因为这是 Dart,而不是 JS,所以 Math.random() 具体不起作用,但您可以在 dart:math 中使用 Random ;)

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]

和另一个答案一样,是pseudo-random,但绝对够用了