【问题标题】:Flutter checkbox state change颤振复选框状态更改
【发布时间】:2020-09-09 01:54:06
【问题描述】:

我试图了解复选框在颤振中的工作原理,但无法理解 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?
    });  
  },  
),  

【问题讨论】:

  • 在我的情况下,复选框值更改为 true,但复选框上没有刻度线。然后它不会变回假。它只是保持打印真实。

标签: flutter


【解决方案1】:

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

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 的 Checkbox 将没有复选标记。一旦你点击你的复选框, onChanged 就会被调用/触发。传递的 onChanged:(bool value) 将等于 !isChecked。它将反转 Checkbox 的当前值的值。现在复选框的值变成了 (isChecked)

【讨论】:

    【解决方案2】:

    应该是statefulWidget

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

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-11-15
        • 1970-01-01
        • 2021-11-19
        • 2021-05-23
        • 1970-01-01
        相关资源
        最近更新 更多