Home > Software design >  flutter - how to display a random name from a list of names
flutter - how to display a random name from a list of names

Time:04-21

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?

CodePudding user response:

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?

CodePudding user response:

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

CodePudding user response:

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';
  • Related