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.
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(),
),
toList?map<T> returns an Iterable<T> instead of a List<T>Iterable that map() returns is lazy. It isn't evaluated yet, only when somebody actually iterates it. Calling toList(), in addition to returning an actual list, forces this evaluation.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
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()
,
),
{} the question is one line functionmap((title) => Tab(text: title)).toList() , so no return needed...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);
Addition to the original answer:
Starting from Dart 2.7, you can now declare extensions to existing classes.
That means that now one can do like so:
extension ListExtension<E> on List<E> {
List<T> mapAsList<T>(T Function(E e) toElement) =>
List<T>.generate(length, (index) => toElement(this[index]));
}
And now this code:
List<int> integerList = [1, 2, 3];
final stringList = integerList.mapAsList((e) => 'Number: $e');
print(stringList);
Will output this, without the need to call .toList() at the end:
[Number: 1, Number: 2, Number: 3]