How do get a random element from a List in Dart?

前端 未结 4 1015
陌清茗
陌清茗 2021-02-05 03:16

How can I retrieve a random element from a collection in Dart?

var list = [\'a\',\'b\',\'c\',\'d\',\'e\'];
4条回答
  •  不思量自难忘°
    2021-02-05 03:59

    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;
    

提交回复
热议问题