'How to print block_data based on block_type key value in dart

I have a method where i iterate through list of objects. For each object i want to print the value of 'block_data' based on "block_type" in the order of above to below. Notice that sometimes the block_type title is above text and sometimes its below text in the list of objects.

Sometimes i have other block_types like graph-pie-chart and i have block_labels for the chart and the block_data for the chart is also in a list based on block_labels. And all the block_type in the List coul be something else and another order. But i still want it in the order of the List of objects i get like the example below. I wonder how i can achieve this with dart?

class Book {
  getBookInfo() {
    final List listOfItems = [
      {"block_type": "title", "block_data": "Books"},
      {"block_type": "text", "block_data": "This is the textblock of books"},
      {"block_type": "text", "block_data": "This is the textblock of publishers"},
      {"block_type": "title", "block_data": "Publishers"},
      {"block_type": "graph-pie-chart", "block_labels": ["Total sold","Sold copies","Reviews"], "block_data": ["3000", "100", "10"]},
      {"block_type": "button", "link": "<link to a bookshop>"},
    ];
    List selectedItem = listOfItems;
    selectedItem.forEach((index) {

      }
      ;
    });
  }
}




Solution 1:[1]

While strictly speaking, you are not incorrect to call each element of the list an object, they are more precisely of type Map<String,String>

You can use .where() to filter out maps that do not have a key of block_type and value of the block type that you need, then do your .forEach() to print the value you want.

You also might consider defining a class type to use instead of a Map in your listOfItems

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Stephen