Search code examples
flutterwidgetflutter-sliver

How to iterate through widgets with different Views


Am beginner in flutter. I have four widgets with different view i.e. BarChart, LineChart, StackedBarChart and CircularChart. Then i created a List

 final List<Widget> widgetList = <Widget>[
    BarChartWidget(), LineChartWidget(), StackedBarChartWidget(), CircularChartWidget(),];

How can i iterate through List of this widgets in ListView

 body: new ListView.separated(
                itemCount: entries.length,
                padding: EdgeInsets.all(8.0),
                itemBuilder: (BuildContext context, int index) {
                  return Container(
                    height: 150,
                    color: Colors.amber[colorCodes[index]],
                    child: new widgetList[index],
                  );
                },
                separatorBuilder: (BuildContext context, int index) => const Divider(),
                )
                );

Solution

  • You were almost there. The issue is:

    child: new widgetList[index],
    

    That's not a valid syntax. You cannot "new" widgetList, as it is a variable.

    Just do:

    child: widgetList[index],
    

    Here's the final syntax:

      new ListView.separated(
        itemCount: entries.length,
        padding: EdgeInsets.all(8.0),
        itemBuilder: (BuildContext context, int index) {
          return Container(
            height: 150,
            color: Colors.amber[colorCodes[index]],
            child: widgetList[index],
          );
        },
        separatorBuilder: (BuildContext context, int index) => const Divider(),
      );