dart - 如何遍历Div中的每个复选框? ( Dart )

标签 dart dart-html

我的html中有一个div:

<div id="list_container_id"></div>

我通过dart向其中添加了复选框

CheckboxInputElement cie = new CheckboxInputElement();
LabelElement label = new LabelElement();
    cie.id="checkboxid_"+asdf;//unique id
    label.htmlFor = 'checkboxid_'+asdf;//bind Label to checkbox
    label.text = asdf;
    list_container.children.add(cie);
    list_container.children.add(label);
    list_container.children.add(new Element.html("<br>"));//linebreak after the checkbox

稍后,我想获得在单击按钮时选中的复选框的所有值的列表。以下代码发生在onClick上:

List list = [];    
for (CheckboxInputElement elem in list_container.children){
        if(elem.checked){
          list.add(elem.value);
        }
      }

据我了解,for循环通过list_container中的每个Checkbox,但是由于某种原因,到达标签时会引发错误:

Breaking on exception: type 'LabelElement' is not a subtype of type 'CheckboxInputElement' of 'elem'.



我不明白为什么当我明确指出elem应该是CheckboxInputElement时,for循环还会困扰Labels。如何做到这一点的正确方法?

最佳答案

您没有声明仅返回CheckboxInputElement,而是声明包含在循环中处理的值的变量仅应保留CheckboxInputElement,但循环会分配它遇到的每个元素。

这样你只得到CheckboxInputElement

List list = [];    
for (var elem in list_container.children.where((e) => e is CheckboxInputElement)){
  if(elem.checked){
    list.add(elem.value);
  }
}

要么

list.addAll(list_container.children
  .where((e) => e is CheckboxInputElement && e.checked)
  .map((e) => e.value));

要么

list.addAll(querySelectorAll('#list_container_id input[type="checkbox"]')
  .where((e) => e is CheckboxInputElement && e.checked)
  .map((e) => e.value));

关于dart - 如何遍历Div中的每个复选框? ( Dart ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25159958/

相关文章:

Dart:将 HTML 处理程序连接到 Dart 源代码

dart - 如何使用window.location.search

flutter - Dart 方法未调用

android - 如何将 json 字符串解码为 UTF-8?

dart - 页面加载事件

web-applications - 是否可以在网络应用程序中写入文件?

dart - 类没有 setter '_scheduler' 的实例

javascript - 如何在 DartPad 中通过鼠标单击获得 X 和 Y?

Flutter resizeToAvoidBottomPadding 挡住整个屏幕

android - 获取 flutter 地点ID的地址