Dart: mapping a list (list.map)

Functional ProgrammingDartFlutter

Functional Programming Problem Overview


I have a list of Strings, e.g.,

var moviesTitles = ['Inception', 'Heat', 'Spider Man'];

and wanted to use moviesTitles.map to convert them to a list of Tab Widgets in Flutter.

Functional Programming Solutions


Solution 1 - Functional Programming

you can use

moviesTitles.map((title) => Tab(text: title)).toList()

example:

    bottom: new TabBar(
      controller: _controller,
      isScrollable: true,
      tabs:
        moviesTitles.map((title) => Tab(text: title)).toList()
      ,
    ),

Solution 2 - Functional Programming

I'm new to flutter. I found that one can also achieve it this way.

 tabs: [
    for (var title in movieTitles) Tab(text: title)
  ]

Note: It requires dart sdk version to be >= 2.3.0, see here

Solution 3 - Functional Programming

Yes, You can do it this way too

 List<String> listTab = new List();
 map.forEach((key, val) {
  listTab.add(val);
 });

 //your widget//
 bottom: new TabBar(
  controller: _controller,
  isScrollable: true,
  tabs: listTab
  ,
),

Solution 4 - Functional Programming

I try this same method, but with a different list with more values in the function map. My problem was to forget a return statement. This is very important :)

 bottom: new TabBar(
      controller: _controller,
      isScrollable: true,
      tabs:
        moviesTitles.map((title) {return Tab(text: title)}).toList()
      ,
    ),

Solution 5 - Functional Programming

tabs: [...data.map((title) { return Text(title);}).toList(), extra_widget],

tabs: data.map((title) { return Text(title);}).toList(),

It's working fine for me

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAbdulMomen عبدالمؤمنView Question on Stackoverflow
Solution 1 - Functional ProgrammingAbdulMomen عبدالمؤمنView Answer on Stackoverflow
Solution 2 - Functional ProgrammingCrackReadView Answer on Stackoverflow
Solution 3 - Functional ProgrammingAlexPadView Answer on Stackoverflow
Solution 4 - Functional ProgrammingMatias de AndreaView Answer on Stackoverflow
Solution 5 - Functional ProgrammingAzhar AliView Answer on Stackoverflow