ToggleButtons in GridView

Viewed 2071

I'm trying to fit each toggle button into each gridview container. Basically with my code all my toggle buttons are trying to fit into one grid view container instead of separated grid view container. Is there any way to mix these two widgets together?

GridView.count(
        crossAxisCount: 2,
        physics: NeverScrollableScrollPhysics(),
        children: <Widget>[
          Padding(
            padding: const EdgeInsets.all(12.0),
            child: ToggleButtons(
              selectedColor: Colors.red,
              isSelected: selected,
              onPressed: onControlPress,
              children: <Widget>[
                Icon(Icons.info),
                Icon(Icons.title),
                Icon(Icons.info),
                Icon(Icons.info),
              ],
            ),
          ),
        ],
      ),
2 Answers

Create ToggleButtons in each grid :

  Widget build(BuildContext context) {
    var counter = 0;

    return GridView.count(
        crossAxisCount: 2,
        children: [
          Icon(Icons.info),
          Icon(Icons.title),
          Icon(Icons.info),
          Icon(Icons.title)
        ].map((widget) {
          final index = ++counter - 1;

          return ToggleButtons(
            selectedColor: Colors.red,
            isSelected: [selected[index]],
            onPressed: (_) => onControlPress(index),
            children: [widget],
          );
        }).toList());
  }

I recommend to use LonelyWolf's answer with this little twitch to it!

GridView.count(
    crossAxisCount: 2,
    children: [
      Icon(Icons.info),
      Icon(Icons.title),
      Icon(Icons.info),
      Icon(Icons.title)
    ].asMap().entries.map((widget) {
      return ToggleButtons(
        selectedColor: Colors.red,
        isSelected: [selected[widget.key]],
        onPressed: (_) => onCapPress(widget.key),
        children: [widget.value],
      );
    }).toList()
Related