Search code examples
pythonlistdartlist-comprehension

Dart equivalent to Python zip and list comprehension for generating list of widgets from two lists


I want to create a list of widgets MyWidget(categoryName, color) from the following two lists.

  static const _categoryNames = <String>[
    'Length',
    'Area',
    'Volume',
  ];

  static const _baseColors = <Color>[
    Colors.teal,
    Colors.orange,
    Colors.pinkAccent,
  ];

In Python I would use a list comprehension with zip to get the result.

my_widget_list = [MyWidget(categoryName, baseColor) for categoryName, baseColor in zip(_categoryNames, _baseColors)]

Googling for a similar method for Dart did not provide any satisfactory solution.


Solution

  • If your aim is to create a list of widgets (assuming both your lists will have same number of elements). You can try

    List<Widget> getWidgets() {
    
      List<Widget> my_widget_list = [];
      const _categoryNames = <String>[
        'Length',
        'Area',
        'Volume',
      ];
    
     const _baseColors = <Color>[
        Colors.teal,
        Colors.orange,
        Colors.pinkAccent,
      ];
    
      for (int i = 0; i <= _categoryNames.length -1 ; i++){
        my_widget_list.add(MyWidget(_categoryNames[i],_baseColors[i]));
      }
    
      return my_widget_list;
      }
    
    Widget MyWidget(String categoryName, Color baseColor){
      return Container(
        color: baseColor,
        child: Text(categoryName,));
    }