In flutter / Dart : how to randomly select a number of items in a list?

Viewed 1423

I have a list of n integers. I would like to randomly select three values out of this list and affect them to a three item list. How can I do that ?

3 Answers

Create this method:

import 'package:collection/collection.dart';

List<int> getList(int n, List<int> source) => source.sample(n);

Usage:

final outputList = getList(3, your_int_list);
print(outputList); // Prints non-repeating 3 random number

Try this exemple with List of String :

import "dart:math";

List<String> list = ['tata','toto','titi','tutu','lala','lolo','lili'];

final random= new Random();

String item= list[random.nextInt(list.length)];
print(item);

With this code select three items from testList1 and add to another list(testList2), but this code sometimes selects the same items. Here is code:

    void getRandomItem(){
    T getRandomElement<T>(List<T> testList1) {
      final random = new Random();
      var i = random.nextInt(testList1.length);
      return testList1[i];
    }
    for(var i=0;i<3;i++){
      var randomItem= getRandomElement(testList1);
      print(randomItem);
      testList2.add(randomItem);
      print(testList2);
    }

  }

button event:

 onPressed: () {
        getRandomItem();
          },
Related