Ad

How To Display A Random Item Of A List? [Every 9 Seconds]

- 1 answer

Is there a way to display a randomQuote every 9 seconds automatically?

Below is a truncated portion of the code that matters:


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

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

:

:

:

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

I've tried your suggested code, but the randomQuote var is not being used. As seen in the images below.

Is the timer periodic at the right place?

randomQuote in scaffold

Error returned of Guillaume's code

Ad

Answer

Quite easy just use a Timer.periodic and define a duration of 9 seconds:

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

Try the full code on DartPad

Ad
source: stackoverflow.com
Ad