Flutter for loop to generate list of widgets

You can try .map Method here,

class Example extends StatelessWidget {

  List <int> exampleList =  [1,2,3,4];

  @override
  Widget build(BuildContext context) {
    return
      Container(
        child: Column(
            children: exampleList.map((i) => new Text(i.toString())).toList()
        ),
      );
  }
}

This method will come in handy if you have objects inside your list. Also with the .map() method .toList() must be used at the end.


You can try this :

@override
  Widget build(BuildContext context) {
    List<int> text = [1,2,3,4];
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Container(
        child: Column(
          children: [
            for ( var i in text ) Text(i.toString())
          ],
        ),
      ),
    );

Note that this was added with the updated of dart to version 2.3. You can read about some of the best changes in this article

Another method that was provided before dart 2.3 is this:

@override
  Widget build(BuildContext context) {
    List<int> text = [1,2,3,4];
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Container(
        child: Column(
          children: List.generate(text.length,(index){
            return Text(text[index].toString());
          }),
        ),
      ),
    );

Tags:

Dart

Flutter