Right now what I do is this:
Row(children: generateWidgets(numbers))
List<Widget> generateWidgets(List<String> numbers){
final widgets List<Widget> = [];
for(int i = 0; i < numbers.length; i ){
widgets.add(Text(numbers[i]))
}
return widgets;
}
I would like to achieve the same thing without needing to make a function and instead have the code of the function as the parameter.
So what i'm looking for is a way to do something more like this:
Row(children: {
final widgets List<Widget> = [];
for(int i = 0; i < numbers.length; i ){
widgets.add(Text(numbers[i]))
}
return widgets;
})
CodePudding user response:
you can use List.generate:
Row(children:
List<Widget>.generate(
numbers.length,
(int index) {
return Text('${numbers[index]}');
},
),
),
CodePudding user response:
This is my method
final List<Widget> listWidget = [];
Row(children: widgets.map((e) => e).toList()),
CodePudding user response:
I will encourage you to use initState
if possible. Also, You can follow @Jim's answer with List.generate
.
And now, about the approach you are trying to use is called anonymous
/inline function
,
Row(
children: () {
// dont prefer doing heavy operatrion
final List<Widget> widgets = [];
for (int i = 0; i < numbers.length; i ) {
widgets.add(Text(numbers[i]));
}
return widgets;
}(),
),
CodePudding user response:
check this ->
Row(children: generateWidgets(numbers))
List<Widget> generateWidgets(List<String> numbers){
return numbers.map((e){
return Text(e.toString());
}).toList();
}