List{dyamic} is not a subtype of List{Widget}

Spread the love

When it would happen:

When we have a function that is used to render (create) widget list and inside it we create a variable that stores that widget in variable of type dynamic. Let’s see by example:

  _renderCols() {
    var cols = [];
    for (int i = 0; i < 2; i++) {
      cols.add(
        Column(children: [Text("Col")]),
      );
    }
    return cols;
  }

// Scaffold function
  @override
  Widget build(BuildContext context) {
    return Row(children: _renderCols());
  }

Above Code will throw error ‘List<dynamic>’ is not a subtype of List<Widget>‘ because we are returning a dynamic type list and flutter does not know what type of data is inside the list. So to fix the above code we must declare ‘cols’ variable in ‘_renderCols’ function as:

List<Widget> cols = [];

Or Specifically:

List<Column> cols = [];

It will solve the issue.

Cheers & Peace Out !!!