Ad

Can I Insert A Widget List Into A GridView?

- 1 answer

I am trying to create a constructor for my Gridview that allows me to pass a list of elements to it and build them in it.

The code is someting like:

GridView menuGrid(BuildContext context, List<MaterialPageRoute> lista) {
  return GridView.count(
    crossAxisCount: 3,
    padding: const EdgeInsets.all(5),
    crossAxisSpacing: 5,
    mainAxisSpacing: 5,
    children: _listado(context, lista),
  );
}

List<Widget> _listado(BuildContext context, List<MaterialPageRoute> lista) {
  List<Widget> _listaWidget = [];
  lista.forEach((element) {
    _listaWidget.add(GestureDetector(
      onTap: () {
        Navigator.push(context, element);
      },
      child: getImageWidgetByMaterialPageRoute(element) is Image
          ? Container(
              padding: const EdgeInsets.all(5),
              child: getImageWidget(getKeyByMaterialPageRoute(element)),
            )
          : Container(
              padding: const EdgeInsets.all(5),
              child: getImageWidgetByMaterialPageRoute(element),
            ),
    ));
  });
  return _listaWidget;
}

But my gridView is blank :(

Ad

Answer

The solution:

GridView menuGrid(
    BuildContext context, List<MaterialPageRoute> lista, int columnas) {
  return GridView.count(
    // Create a grid with 2 columns. If you change the scrollDirection to
    // horizontal, this produces 2 rows.
    crossAxisCount: columnas,
    padding: const EdgeInsets.all(20),
    crossAxisSpacing: 10,
    mainAxisSpacing: 10,
    children: <Widget>[
      ..._listado(context, lista),
    ],
  );
}
List<Widget> _listado(BuildContext context, List<MaterialPageRoute> lista) {
  List<Widget> _listaWidget = [];
  lista.forEach((element) {
    _listaWidget.add(GestureDetector(
      onTap: () {
        Navigator.push(context, element);
      },
      child: Container(
        padding: const EdgeInsets.all(5),
        child: getWidgetByMaterialPageRoute(element) is Image
            ? Container(
                padding: const EdgeInsets.all(8),
                decoration: BoxDecoration(
                  image: DecorationImage(
                    image: getImageWidgetByMaterialPageRoute(element).image,
                    fit: BoxFit.cover,
                  ),
                ),
              )
            : getImageWidget(getKeyByMaterialPageRoute(element)),
      ),
    ));
  });
  return _listaWidget;
}

The solution was in the way of calling the list:

children: [ ..._listado(context, lista), ]

Greetings

Ad
source: stackoverflow.com
Ad