How to get a random item from a list in a darth?

How to get a random item from a collection in Dart?

var list = ['a','b','c','d','e']; 
+6
source share
3 answers
 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)]; 
+21
source

This also works:

 var list = ['a','b','c','d','e']; var randomItem = (list..shuffle()).first; 

or, if you do not want to spoil the list, create a copy:

 var randomItem = (list.toList()..shuffle()).first; 
+5
source

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); 
0
source

Source: https://habr.com/ru/post/1489784/


All Articles