Flutter for loop to generate list of widgets

FlutterDart

Flutter Problem Overview


I have code like this but I want it to iterate over an integer array to display a dynamic amount of children:

return Container(
  child: Column(
    children: <Widget>[
      Center(
        child: Text(text[0].toString(),
            textAlign: TextAlign.center),
      ),
      Center(
        child: Text(text[1].toString(),
            textAlign: TextAlign.center),
      ),
    ],
  ),
)

Where the text variable is a list of integers converter to string here. I tried adding a function to iterate through the array and display the 'children' but was getting a type error. Not sure how to do it since I'm new to Dart and Flutter.

Flutter Solutions


Solution 1 - Flutter

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

Solution 2 - Flutter

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.

Solution 3 - Flutter

Assuming you want to loop some widgets (e.g Text()) in the Column widget, you can add a loop inside the children property. See a sample below:

Column(
   children: <Widget>[
      for (int i=0; i<3; i++)
         Text("Hello" + i)
   ],
)

Solution 4 - Flutter

You could use the map method of your list of Strings.

 Widget _getListWidgets(List<String> yourList){
    return Row(children: yourList.map((i) => Text(i)).toList());
  }

When your List have a complex Object:

Widget _getListWidgets( List<YourObject> lstItens) {
  return Row(children: lstItens.map((i) => Text(i.name)).toList());
}

Solution 5 - Flutter

DartPad: Code Snippet

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(context) => MaterialApp(
    home: HomePage()
  );
}


class HomePage extends StatelessWidget {
  @override
  Widget build(context) => Scaffold(
    appBar: AppBar(title: Text("test")),
    body: SafeArea(
        child:Center(
          child:
          Row(
            children: [
              Container(
                width: MediaQuery.of(context).size.width-200.0,
                child: Content()
              )
            ]
          )
        )
    )
  );
}

class Content extends StatelessWidget {
  final List<String> elements = ["Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "A Million Billion Trillion", "A much, much longer text that will still fit"];
  @override
  Widget build(context) => GridView.builder(
    itemCount: elements.length,
    gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
      maxCrossAxisExtent: 130.0,
      crossAxisSpacing: 20.0,
      mainAxisSpacing: 20.0,
    ),
    itemBuilder: (context, i) => Card(
      child: Center(
        child: Padding(
          padding: EdgeInsets.all(8.0), child: Text(elements[i])
        )
      )
    )
  );
}

And also you do it like this way

return new ListView(
  children: new List.generate(10, (index) => new ListTile()),
);

Solution 6 - Flutter

The best way to do this is to make use of the List.map()

That way you do not have to enable 'control-flow-collections'

 Container(
        child: Column(
            children: myList.map((e) => new Text(e)).toList(),
          ),
   );

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionHasenView Question on Stackoverflow
Solution 1 - FlutterAbbas.MView Answer on Stackoverflow
Solution 2 - FlutterSahan AmarshaView Answer on Stackoverflow
Solution 3 - FlutterEawebView Answer on Stackoverflow
Solution 4 - FlutterCassio SeffrinView Answer on Stackoverflow
Solution 5 - FlutterParesh MangukiyaView Answer on Stackoverflow
Solution 6 - FlutterRnDrxView Answer on Stackoverflow