How do get a random element from a List in Dart?
import "dart:math";
var list = ['a','b','c','d','e'];
// generates a new Random object
final _random = new Random();
// generate a random index based on the list length
// and use it to retrieve the element
var element = list[_random.nextInt(list.length)];
This works too:
var list = ['a','b','c','d','e'];
//this actually changes the order of all of the elements in the list
//randomly, then returns the first element of the new list
var randomItem = (list..shuffle()).first;
or if you don't want to mess the list, create a copy:
var randomItem = (list.toList()..shuffle()).first;
import "dart:math";
var list = ['a','b','c','d','e'];
list[Random().nextInt(list.length)]
You can use the dart_random_choice package to help you.
import 'package:dart_random_choice/dart_random_choice.dart';
var list = ['a','b','c','d','e'];
var el = randomChoice(list);