Home > OS >  How to fetch a random mention from the model?
How to fetch a random mention from the model?

Time:10-25

I'm new to model writing and I need your help.

I write a code like this:

import 'dart:js';
import 'dart:math';

List AllWords = [{"ID": 0, "Word": "This is words.", "Author": "Emir"}, {"ID": 1, "Word": "This is words.", "Author": "Jack"}];

class Words {
  final int ID;
  final String Word;
  final String Author;
  Words(this.ID, this.Word, this.Author);
  void GetWords() {
    final _random = new Random();
    var Words = AllWords[_random.nextInt(AllWords.length)];
    return Words;
  }
}

My goal is to fetch a random word from the list when I use the GetWords Function. Is this code correct? How can I use this code I wrote in main.dart?

Thanks for help.

CodePudding user response:

try this :

import 'dart:math' as math;

//your list is a map, not a `Words` class
//if your list is a `Words` class, it will be like this :
//final allWords = [Words(Id,words,author), Words()}

List<Map<String, Object?>> allWords = [
  {"ID": 0, "Word": "This is words.", "Author": "Emir"},
  {"ID": 1, "Word": "This is words.", "Author": "Jack"}
];

class Words {
  final int iD;
  final String word;
  final String author;

  Words({required this.iD, required this.author, required this.word});

  factory Words.fromJson(Map<String, Object?> json) {
    return Words(
        iD: json['ID'] as int,
        author: json['Author'] as String,
        word: json['Word'] as String);
  }

  factory Words.getRandomWord() {
    math.Random random = math.Random();
    return Words.fromJson(allWords[random.nextInt(allWords.length - 1)]);
  }
}

//Somewhere else in your code
Words myWord = Words.getRandomWord();
  •  Tags:  
  • dart
  • Related