Home > Back-end >  Flutter For Loop inside children only allows one widget
Flutter For Loop inside children only allows one widget

Time:04-02

I have a For loop inside a listview widget to populate its children. Right now I have one widget my custom history view widget:

  Expanded(
    flex: 5,
    child: Container(
      width: double.infinity,
      color: Colors.white,
      child: ListView(
        padding: const EdgeInsets.only(top: 10.0),
        children: [
          for (var i = Provider.of<WeekList>(context)
                  .listOfWeeks
                  .toList()
                  .length;
              i > 1;
              i--)
            HistoryView(index: i - 2),
        ],
      ),
    ),
  )

The problem is I want to add a second widget under the History view widget, but I cant seem to figure out how to correctly do this. I thought it would be as easy as this:

      Expanded(
        flex: 5,
        child: Container(
          width: double.infinity,
          color: Colors.white,
          child: ListView(
            padding: const EdgeInsets.only(top: 10.0),
            children: [
              for (var i = Provider.of<WeekList>(context)
                      .listOfWeeks
                      .toList()
                      .length;
                  i > 1;
                  i--){
                      HistoryView(index: i - 2),
                      WeekWidget(index: i - 2 ),
                  }
                
            ],
          ),
        ),
      )

CodePudding user response:

You can wrap HistoryView and WeekWidget in a column

CodePudding user response:

Use the spread operator

      Expanded(
        flex: 5,
        child: Container(
          width: double.infinity,
          color: Colors.white,
          child: ListView(
            padding: const EdgeInsets.only(top: 10.0),
            children: [
              for (var i = Provider.of<WeekList>(context)
                      .listOfWeeks
                      .toList()
                      .length;
                  i > 1;
                  i--)
                      ...[
                      HistoryView(index: i - 2),
                      WeekWidget(index: i - 2 ),
                    ],                
            ],
          ),
        ),
      )
  • Related