list - 通过循环渲染复选框

标签 list flutter user-interface dart checkbox

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存储在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...
    );
  }
}

关于list - 通过循环渲染复选框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63379498/

相关文章:

python - 将对象列表的字符串表示形式转换回 python 中的列表

ios - Flutter firebase_auth 中的无效应用程序凭据/ token 不匹配

flutter - 如何在 Flutter 中使用 Agora 实现 Callkeep?

javascript - 为克隆输入提供输入 'name' 属性,该属性位于列表内

randomForest::combine() 和列表中的对象

c# - 如果对象不为空,则将对象添加到列表的简写

flutter - Flutter中离开页面后停止播放音乐

python - 如何在Python脚本中途暂停并恢复它?

java - 为什么我的框架没有调整大小?

javascript - 使用 SVG 作为渲染器的 GUI 库?