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

前端 未结 4 1014
陌清茗
陌清茗 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:55

    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 讨论(0)
  • 2021-02-05 03:56
    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)];
    
    0 讨论(0)
  • 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;
    
    0 讨论(0)
  • 2021-02-05 04:01
    import "dart:math";
    
    var list = ['a','b','c','d','e'];
    
    list[Random().nextInt(list.length)]
    
    0 讨论(0)
提交回复
热议问题