分接开关状态不变

时间:2020-04-24 09:08:23

标签: flutter

我想在点击时更改开关的状态,但它不会更改。仅当我拖动切换图块按钮时,状态才会更改。

                    padding: const EdgeInsets.only(
                        top: 12.0, bottom: 12.0, right: 8.0),
                    child: Column(
                      mainAxisSize: MainAxisSize.min,
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: <Widget>[
                        Switch(
                            value: switchValue,
                            onChanged: (bool value) {
                              setState(() {
                                switchValue = value;
                              });
                            }),
                        Text(
                          "Check-in",
                          style: TextStyle(fontSize: 13, color: Colors.grey),
                        )
                      ],
                    ),
                  )```

1 个答案:

答案 0 :(得分:0)

您需要将setState()移出Slider的外部,然后再进行构建(如下所示)才能使其正常工作

  bool switchValue = false;
  void _changeSwitch(bool value) {
    setState(() {
      switchValue = !switchValue;
    });
  }

  @override
  Widget build(BuildContext context) {

...

 Switch(value: switchValue, onChanged: _changeSwitch),

如果有兴趣,请参见使用setState()的更多详细信息:https://medium.com/flutter-community/flutter-state-management-setstate-fn-is-the-easiest-and-the-most-powerful-44703c97f035