-1

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;
})

4 Answers4

1

you can use List.generate:

Row(children:
  List<Widget>.generate(
    numbers.length,
    (int index) {
      return Text('${numbers[index]}');
    },
  ),
),
Jim
  • 6,928
  • 1
  • 7
  • 18
0

This is my method

final List<Widget> listWidget = [];
Row(children: widgets.map((e) => e).toList()),
Atlas59
  • 1
  • 1
0

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;
  }(),
),
Md. Yeasin Sheikh
  • 54,221
  • 7
  • 29
  • 56
-1

check this ->

Row(children: generateWidgets(numbers))

List<Widget> generateWidgets(List<String> numbers){
   return numbers.map((e){
     return Text(e.toString());
  }).toList();
}
Sonu Saini
  • 1,814
  • 9
  • 16