繁体   English   中英

Flutter 复选框状态更改

[英]Flutter checkbox state change

我试图了解复选框在颤振中的工作方式,但无法了解以下代码中 isChecked 的值如何从 false 变为 true。

即我们在哪里指定 isChecked= true?

bool isChecked = false;

Checkbox(  
  value: isChecked,   
  onChanged: (bool value) {  
    setState(() {  
      isChecked = value;   
      print(isChecked)     // How did value change to true at this point?
    });  
  },  
),  

它应该是一个statefulWidget

class _MyAppState extends State<MyApp> {
 bool isChecked = false; // here
@override
Widget build(BuildContext context) {
  return ...;
 }
}

复选框是一种保存布尔值的输入组件。 它是一个 GUI 元素,允许用户从多个选项中选择多个选项。 在这里,用户只能回答是或否值。 标记/选中的复选框表示是,未标记/未选中的复选框表示没有值。 通常,我们可以将屏幕上的复选框视为带有空白或刻度线的方框。 每个复选框对应的标签或标题描述了复选框的含义。

在本文中,我们将学习如何在 Flutter 中使用复选框。 在 Flutter 中,我们可以有两种类型的复选框:名为“checkbox”的 Checkbox 的紧凑版本和带有标题和副标题的“CheckboxListTile”复选框。 复选框:

value   It is used whether the checkbox is checked or not.
onChanged   It will be called when the value is changed.
Tristate    It is false, by default. Its value can also be true, false, or null.
activeColor It specified the color of the selected checkbox.
checkColor  It specified the color of the check icon when they are selected.
materialTapTargetSize   It is used to configure the size of the tap target.a

让我们试着一一理解代码:

bool isChecked = false;
Checkbox(  
  value: isChecked,   
  onChanged: (bool value) {  
    setState(() {  
      isChecked = value;   
      print(isChecked)     // How did value change to true at this point?
    });  
  },  
),  

您在顶部声明了一个布尔值,它以 false 值开头。 接下来,您已经创建了一个复选框。 复选框的值是您的布尔值。 这就是为什么它的值一开始是假的,一个值为假的复选框将没有复选标记。 单击复选框后,onChanged 将被调用/触发。 传递的 onChanged:(bool value) 将等于 !isChecked。 它将反转 Checkbox 的当前值的值。 现在复选框的值变成了 (isChecked) <- 当前值为 false 所以 (bool value) <- value 变为 true,调用 setState 将告诉所有小部件重建。 现在您已经更改了 setState 中的值,CheckBox 的值将为 true,从而被检查。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM