'flutter - how to display a random name from a list of names

Please how do you display a random name from a list of names in flutter? for example List names = ['jerry','mark','john'];

how do i display a random name?



Solution 1:[1]

please try this code:

import "dart:math";

List names = ['jerry','mark','john'];

// 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 = names[_random.nextInt(names.length)];

This method would also work:

var randomName = (names.toList()..shuffle()).first;

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

Solution 2:[2]

You can generate a random number from 0 until the list size and then use it as a index to get a random element.

Solution 3:[3]

You can use the dart:math package and its Random object. This will display a random name from your array every time the widget is rebuilt.

Text(names[Random().nextInt(names.length - 1)])

You will have to add

import 'dart:math';

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Shafee Silent
Solution 3 eimmer