skip to Main Content

I am trying to make a class of Dictionary. Registering a word with a definition.

However, I am stuck where I am trying to input a word and to return a definition. Since I am using a list of maps. I can’t really figure out what kind of list methods should I use. I know that I need to iterate a list until it matches the value ‘apple’ and return the value of ‘red’. But how?

List<Map<String, String>> wordList = [];
void main() {
  Dictionary.add({'term': 'apple', 'definition': 'red'});
  Dictionary.add({'term': 'banana', 'definition': 'yellow'});

  Dictionary.get('apple'); // THIS SHOULD RETURN 'red'
}

class Dictionary {
  late String term;
  late String definition;

  Dictionary.add(Map<String, String> word) {
    term = word['term']!;
  definition = word['definition']!
    wordList.add(word);
    words.add(term);
  }

  static void get(String word) {
    //FIX ME:
    if()
  }

2

Answers


  1. I think you just need a Map<String, String> for these use-case.
    You could define

    Map<String, String> wordList = {};
    wordList['apple'] = 'red';
    wordList['banana'] = 'yellow';
      
    // Usage
    debugPrint(wordList['apple']);
    

    Your class should not include a variable from outside. This approach … i think it’s not good.

    Login or Signup to reply.
  2. Move wordList to your dictionary class, it does not make sens to keep it outside and create a method inside the class to return somrthing from the list:

    static List<Map<String, String>> wordList = [];
    

    Then get rid of this line:

    words.add(term);
    

    get method:

    static String get(String word) {
      for (var i = 0; i < wordList.length; i++) {
        if (wordList[i]['term'] == word) {
          return wordList[i]['definition'];
        }
      }
      return '';
    }
    

    then you call it this way:

    Dictionary.get('apple')
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search