getRandomValueByFieldName method

String getRandomValueByFieldName(
  1. String fieldname
)

Retrieves a random value from an element in the current Iterable based on the specified fieldname.

The function creates a Random generator to generate a random index within the range of the Iterable's length. It uses the nextInt() method of the generator to obtain a random integer index. It then retrieves the element at the generated index from the Iterable by converting it to a List using toList(). The function assumes that the retrieved element is of type T. It accesses the value associated with the specified fieldname in the retrieved element, assuming the element is of type Map.

Returns a random value associated with the specified fieldname.

Example:

List<Map<String, dynamic>> data = [
  {'name': 'Alice', 'age': 25},
  {'name': 'Bob', 'age': 30},
  {'name': 'Charlie', 'age': 35},
];

String randomName = data.getRandomValueByFieldName('name');
print(randomName); // Output: Randomly selected name from the list

Implementation

String getRandomValueByFieldName(String fieldname) {
  Random generator = Random();
  final index = generator.nextInt(this.length);
  T result = this.toList()[index];

  return (result as Map)[fieldname];
}