Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add children to the column dynamically in flutter

Tags:

flutter

dart

How to add 4 children or some cases it will be 3 or 2 to the column in the flutter.

        Column(
          children: <Widget>[_weatherData],
        )
like image 322
K K Muhammed Fazil Avatar asked Nov 22 '19 06:11

K K Muhammed Fazil


2 Answers

If you want to add Widget dynamically,

  List<Widget> data() {
    List<Widget> list = List();
    //i<5, pass your dynamic limit as per your requirment 
    for (int i = 0; i < 5; i++) {
      list.add(Text("Index $i"));//add any Widget in place of Text("Index $i")
    }
    return list;// all widget added now retrun the list here 
  }

Now add this list into your column,

 Column(
    mainAxisSize: MainAxisSize.max,
    children: data(),
    ),

OutPut:

enter image description here

like image 99
Ravinder Kumar Avatar answered Nov 17 '22 07:11

Ravinder Kumar


If you know beforehand which Widgets you want to add, you can use inline if statements when building the children:

Column(
     children: <Widget>[
     if(condition1)
      widget1,
     if(condition2)
     widget2,
_    weatherData,
],)

or if you do not know beforehand, you can call a function there that returns a List<Widget>.

Using the spread operator (...) you can even mix and match:

Column(
     children: <Widget>[
     if(condition1)
      widget1,
     if(condition2)
     widget2,
_    ..._getWeatherDataWidgets(),
],)

Hope this helps.

like image 33
lyio Avatar answered Nov 17 '22 06:11

lyio