Flutter复选框状态更改

时间:2020-09-09 01:54:06

标签: flutter

我试图了解复选框在波动中的工作方式,而无法理解在下面的代码中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?
    });  
  },  
),  

3 个答案:

答案 0 :(得分:0)

它应该是statefulWidget

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

答案 1 :(得分:0)

复选框是一种包含布尔值的输入组件。它是一个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

答案 2 :(得分:0)

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

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

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

相关问题