list - 通过循环渲染复选框
问题描述
void filterList(BuildContext context) {
showModalBottomSheet(
context: context,
builder: (bContext) {
return FilterList();
},
);
}// creating a bottom modal sheet
class FilterList extends StatefulWidget {
@override
_FilterListState createState() => _FilterListState();
}//creating a state for checkboxes
class _FilterListState extends State<FilterList> {
int i;
bool checkvalue = false;
Widget _element(String id) {
return Row(
children: <Widget>[
Checkbox(
value: checkvalue,
onChanged: (value) {
setState(
() {
checkvalue = value;
},
);
},
),
Text('$id')
],
);
}// A new Widget where I get to combine the checkboxes with their respective texts
@override
Widget build(BuildContext context) {
return ListView(
children: <Widget>[for (i = 10; i <= 120; i = i + 10) _element('$i HP')],
// for loop for iterating the widget rendering
//HP stands for horsepower...
);
}
}
因此,我尝试在底部模式表内创建过滤器 UI 时使用“for循环”呈现复选框。在这里,当我尝试更改一个复选框的状态时,所有其他复选框的状态也会更改。有没有办法让我保留 for 循环,但只更改所选复选框的状态?或者,我是否必须一直放弃循环和硬编码?
解决方案
您需要将所有checkvalue
s 存储在 a 中List
:
class FilterList extends StatefulWidget {
@override
_FilterListState createState() => _FilterListState();
} //creating a state for checkboxes
class _FilterListState extends State<FilterList> {
int i;
List<bool> checkvalue = new List<bool>.filled(12, false); // this is new
Widget _element(String id, int index) { // index added
return Row(
children: <Widget>[
Checkbox(
value: checkvalue[index], // [index] added
onChanged: (value) {
setState(
() {
checkvalue[index] = value; // [index] added
},
);
},
),
Text('$id')
],
);
} // A new Widget where I get to combine the checkboxes with their respective texts
@override
Widget build(BuildContext context) {
return ListView(
children: <Widget>[
for (i = 10; i <= 120; i = i + 10) _element('$i HP', i ~/ 10 - 1) // index added
],
// for loop for iterating the widget rendering
//HP stands for horsepower...
);
}
}
推荐阅读
- javascript - 从strapi插件前端运行节点脚本
- amazon-web-services - 如何将资源 ID 导入 Cloudformation 中的 UserData
- javascript - 如何使浏览器窗口更小?
- php - 单击php中的按钮时将数据插入MySQL
- javascript - Firebase Firestore .get() 未返回预期数据
- reactjs - 检测 DOM 加载完成
- reactjs - 无法对 Reactjs 中的未安装组件警告执行 React 状态更新
- apache - 重写到子目录,然后使用 root .htaccess 重写到 React 的 index.html
- php - POST请求在mysql自动增量ID前面添加空格
- python-3.x - 无法手动或从代码将窗口宽度调整为小于固定值