Flutter ToggleButtons报错'children.length == isSelected.length'如何解决?
报错原因
ToggleButtons组件有强制约束:单个ToggleButtons实例的children属性长度必须和isSelected数组长度必须完全相等。你当前代码遍历4个Text组件时,为每个Text单独生成了一个ToggleButtons组件,每个ToggleButtons的children只有1个元素,但传入的isSelected是长度为4的_selections数组,1≠4因此触发断言报错。
同时你的用法不符合ToggleButtons的设计逻辑:ToggleButtons本身就是用来管理一组可选择按钮的组件,不需要嵌套GridView就能实现多按钮同行布局。
修复方案
方案1:直接使用ToggleButtons原生实现(推荐)
不需要嵌套GridView,直接将4个Text作为ToggleButtons的children,满足长度匹配要求,代码如下:
List<bool> _selections = [false, false, false, false]; ToggleButtons( onPressed: (int index) { setState(() { // 单选逻辑:仅选中当前点击的按钮 for (int buttonIndex = 0; buttonIndex < _selections.length; buttonIndex++) { _selections[buttonIndex] = buttonIndex == index; } }); }, isSelected: _selections, // children长度为4,和_isSelected长度一致,满足断言要求 children: const [ Text("one"), Text("two"), Text("three"), Text("four"), ], )
如果需要让按钮撑满一行,可以搭配Row和Expanded使用,也可以通过ToggleButtons的constraints、padding等属性调整布局样式。
方案2:保留GridView实现(不推荐)
如果确实需要用GridView的网格布局逻辑,不要为每个按钮单独实例化ToggleButtons,替换为普通按钮自行管理选中状态即可:
List<bool> _selections = [false, false, false, false]; final _buttonLabels = ["one", "two", "three", "four"]; GridView.count( crossAxisCount: 4, children: List.generate(_buttonLabels.length, (index) { return TextButton( onPressed: () { setState(() { for (int i = 0; i < _selections.length; i++) { _selections[i] = i == index; } }); }, style: TextButton.styleFrom( // 模拟ToggleButtons选中样式 backgroundColor: _selections[index] ? Colors.blue : Colors.transparent, foregroundColor: _selections[index] ? Colors.white : Colors.black, ), child: Text(_buttonLabels[index]), ); }).toList() )
内容的提问来源于stack exchange,提问作者J0nathan Lam
相关产品推荐
相关产品推荐

