android – the element type 'List<widget>' can't be assigned to the list type 'Widget'-ThrowExceptions

Exception or error:

I am trying to add data using for loop in gridview but it is showing some error. Here is my code for component

return new GridView.count(
    crossAxisCount: 2,
    padding: const EdgeInsets.all(10.0),
    crossAxisSpacing: 10.0,
    mainAxisSpacing: 10.0,
    children: <Widget>[getList()],
);

getList() code

List<Widget> getList() {
  List<Widget> childs = [];
  for (var i = 0; i < 10; i++) {
    childs.add(new ListItem('abcd ' + $i));
  }
  return childs;
}

But it is showing compile time error.

The element type 'List<widget>' can't be assigned to the list type 'Widget'
How to solve:

Here you are wrapping a list as list

children: <Widget>[getList()],

This should rather be

children: getList(),

###

Since the answer was not satisfactory for me, so I found another solution.

Flutter gives you the possibility to write conditions on a single line also in the graphic, so you can insert a cycle on a single line and then insert the other different widgets. This is a practical example in response to the main question:

 Column(
    children: <Widget>
      [
        for (int i = 0;
        i < workouts.series.length;
        i++)
          "//CREATE N YOUR WIDGETS//",
          new Text(
          "${workouts.series.length} x ${exerciseWorkout.repsToDo} ",
          style: TextStyle(
          color: Colors.black87,
          fontSize: 16,
          fontWeight: FontWeight.bold),
          )
      ],
     )

###

Just use spread operator:

return new GridView.count(
    crossAxisCount: 2,
    padding: const EdgeInsets.all(10.0),
    crossAxisSpacing: 10.0,
    mainAxisSpacing: 10.0,
    children: <Widget>[...getList()],
);

###

In Flutter 1.12.13+hotfix.7 and Dart 2.7.0, we can iterate over the list of objects as follows:

Iterate over the list of objects

...data.map((f) => paragraph(f.title, f.description)).toList(),

Custom widget

Column paragraph(String title, String description) {
  return new Column(
    children: <Widget>[
      Container(
        margin: EdgeInsets.only(bottom: 15),
        child: Text(
          title,
          style:
              TextStyle(fontWeight: FontWeight.normal, color: Colors.black38),
        ),
      ),
      Container(
        child: Text(
          description,
          style: TextStyle(fontWeight: FontWeight.bold, color: Colors.black38),
        ),
      ),
    ],
  );
}

Data: List of objects

List<AboutUsData> data = [
    new AboutUsData(
      title: 'Our Vision',
      description:
          'OUR VISION',
    ),
    new AboutUsData(
      title: 'Our Mission',
      description:
          'OUR MISSION',
    ),
    new AboutUsData(
      title: 'Our Values',
      description:
          'As we grow as a company',
    ),
  ];

Leave a Reply

Your email address will not be published. Required fields are marked *