Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ToggleButtons in GridView

Tags:

flutter

dart

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),
              ],
            ),
          ),
        ],
      ),
like image 951
LonelyWolf Avatar asked Feb 23 '20 15:02

LonelyWolf


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());
  }
like image 192
Kahou Avatar answered Nov 05 '22 20:11

Kahou


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()
like image 2
marl Avatar answered Nov 05 '22 22:11

marl