Home > OS >  Fluttter categories list base on another list of data
Fluttter categories list base on another list of data

Time:01-05

I have two list and need to get the category of each words and display it as a group. my first list is where data is coming from.

final WordsList = [
  {
    'category': 'category-1',
    'words': ['Happy', 'Excited', 'Playful', 'Content', 'Grateful', 'Inspired']
  },
  {
    'category': 'category-2',
    'words': ['Confused', 'Doubtful','Confused']
  },
  {
    'category': 'category-3',
    'words': ['Scared','Horrified']
  },

Then the second list is from the user selection

List userSelection = [Happy, Confused, Doubtful, Scared, Horrified];

What i want to achieve is below.

Category-1 Category-2 Category-3
Happy Confused Scared
Doubtful Horrified

Here is my code so far what i did was iterate the userSelection list and search the words from the WordsList and was able to retrieve the list but cannot figure it out how to display it properly.

void getCategory() {
    var wordsDisplay = [];
    for (var i = 0; i < userSelection.length; i  ) {
      wordsDisplay.add(WordsList
          .where((element) => (element["words"].contains(userSelection[i]))));
    }
  }

CodePudding user response:

Try this out:

void main() {
  List<Map<String, dynamic>> wordsList = [
    {
      'category': 'category-1',
      'words': [
        'Happy',
        'Excited',
        'Playful',
        'Content',
        'Grateful',
        'Inspired'
      ]
    },
    {
      'category': 'category-2',
      'words': ['Confused', 'Doubtful', 'Confused']
    },
    {
      'category': 'category-3',
      'words': ['Scared', 'Horrified']
    },
  ];

  // using a set to eliminate duplicates like 'Confused' in category-2
  Set<String> userSelection = {
    'Happy',
    'Confused',
    'Doubtful',
    'Scared',
    'Horrified',
  };

  List<Map<String, dynamic>> wordsDisplay = [
    for (final category in wordsList)
      {
        // copy category into a new map
        ...category,
        // overwrite the 'words' key/value pair
        // the items we want are the set intersection of the userSelection
        // and the original words list.
        'words': userSelection.intersection({...?category['words']}),
      },
  ];

  print(wordsDisplay);
}
  •  Tags:  
  • Related