首页 > 解决方案 > 如何显示列表的随机项?[每 9 秒]

问题描述

有没有办法每 9 秒自动显示一个 randomQuote?

下面是重要的代码的截断部分:


final List<String> RandomQuotes = [ ... ] // (one hundreds quotes here)

var randomQuote = (RandomQuotes.toList()..shuffle()).first;

:

:

:

... Text(randomQuote, Style:...)

我已经尝试过您建议的代码,但没有使用 randomQuote 变量。如下图所示。

计时器是否在正确的位置周期性?

脚手架中的随机引用

Guillaume 的代码返回错误

标签: listflutterrandom

解决方案


很简单,只需使用 aTimer.periodic并定义 9 秒的持续时间:

import 'dart:async';
import 'dart:math';

final items = <String>['Hi', 'Hello', 'Test'];

Timer.periodic(Duration(seconds: 9), (_) {
  final _random = Random();
  final item = items[_random.nextInt(items.length)];
  print(item);
});

在 DartPad 上试用完整代码


推荐阅读