How do get a random element from a List in Dart?
DartDart Problem Overview
How can I retrieve a random element from a collection in Dart?
var list = ['a','b','c','d','e'];
Dart Solutions
Solution 1 - 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)];
Solution 2 - Dart
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;
Solution 3 - Dart
import "dart:math";
var list = ['a','b','c','d','e'];
list[Random().nextInt(list.length)]
Solution 4 - Dart
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);
Solution 5 - Dart
I just created an extension method for List.
import 'dart:math';
extension RandomListItem<T> on List<T> {
T randomItem() {
return this[Random().nextInt(length)];
}
}
We can use it like this.
List.randomItem()
example :
Scaffold(
body: SafeArea(
child: isItLogin
? Lottie.asset('assets/lottie/53888-login-icon.json')
: Lottie.asset(LottieAssets.loadingAssets.randomItem()),
),
);
Solution 6 - Dart
var list = ['a','b','c','d','e'];
list.elementAt(Random().nextInt(list.length));