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

Dart

Dart Problem Overview


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

var list = ['a','b','c','d','e'];

Dart Solutions


Solution 1 - Dart

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)];

Solution 2 - Dart

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;

Solution 3 - Dart

import "dart:math";

var list = ['a','b','c','d','e'];

list[Random().nextInt(list.length)]

Solution 4 - Dart

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

Solution 5 - Dart

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()),
      ),
    );

Solution 6 - Dart

var list = ['a','b','c','d','e'];
list.elementAt(Random().nextInt(list.length));

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNik GrafView Question on Stackoverflow
Solution 1 - DartNik GrafView Answer on Stackoverflow
Solution 2 - DartJerome PuttemansView Answer on Stackoverflow
Solution 3 - DartRazi KallayiView Answer on Stackoverflow
Solution 4 - DartKirollos MorkosView Answer on Stackoverflow
Solution 5 - Dart763View Answer on Stackoverflow
Solution 6 - DartDiyorbekDevView Answer on Stackoverflow