155

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.

lrn
  • 64,680
  • 7
  • 105
  • 121

6 Answers6

236

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()
      ,
    ),
39

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

CrackRead
  • 407
  • 4
  • 3
7

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
  ,
),
AlexPad
  • 10,364
  • 3
  • 38
  • 48
6

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()
      ,
    ),
Matias de Andrea
  • 194
  • 2
  • 11
4
tabs: [...data.map((title) => Text(title)).toList(), extra_widget],

tabs: data.map((title) => Text(title)).toList(),

It's working fine for me

Community
  • 1
  • 1
Azhar Ali
  • 1,961
  • 3
  • 13
  • 24
0

small addition to the AbdulMomen عبدالمؤمن answer: for better performance you should set grawable false if list will not grow.

moviesTitles.map((title) => Tab(text: title)).toList(growable: false);
Vladyslav Ulianytskyi
  • 1,401
  • 22
  • 22