Reputation: 3739
How can I retrieve a random element from a collection in Dart?
var list = ['a','b','c','d','e'];
Upvotes: 109
Views: 77352
Reputation: 1
Also we can create CurrentStatu likes Whatsapp in following code
I used your answer , thx bro
import 'dart:math';
void main(){
var list = [0,1];
//TODO generates a new Random object with for()
final _random = new Random();
var element = list[_random.nextInt(list.length)];
Status Statuscurrent = Status.values.elementAt(element);
print(Statuscurrent);
}
enum Status{
online,
offline
}
Upvotes: 0
Reputation: 1770
import 'dart:math';
final _random = Random();
// from MIN(inclusive), to MAX(inclusive).
int randomBetweenIncInc(int min, int max) => min + _random.nextInt((max + 1) - min);
var list = ['a','b','c','d','e'];
var element = list[randomBetweenIncInc(0, list.length - 1)];
Upvotes: 2
Reputation: 2774
This is provided by the collection package's IterableExtension.sample() method:
import 'package:collection/collection.dart';
var list = ['a','b','c','d','e'];
print(list.sample(1).single);
Example output:
e
Note that the method is generalized to return N samples of the list.
Upvotes: 8
Reputation: 774
var list = ['a','b','c','d','e'];
list.elementAt(Random().nextInt(list.length));
Upvotes: 7
Reputation: 1693
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()),
),
);
Upvotes: 17
Reputation: 900
import "dart:math";
var list = ['a','b','c','d','e'];
list[Random().nextInt(list.length)]
Upvotes: 31
Reputation: 1113
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;
Upvotes: 99
Reputation: 2711
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);
Upvotes: 11
Reputation: 3739
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)];
Upvotes: 180