【问题标题】:How do I add controllers to custom widgets in flutter如何在颤动中将控制器添加到自定义小部件
【发布时间】:2020-02-10 13:22:33
【问题描述】:

我有一个父小部件,它调用我制作的自定义 Switch 小部件。我需要父小部件中的开关值(无论是打开还是关闭)。我可以在我的开关小部件中创建一个控制器来返回该值吗?

目前,我正在从我的父小部件传递函数,该函数根据开关小部件中的开关值更改我的父小部件中的布尔值。

父小部件:

bool isSwitchOn = false;
Switch(onSwitchToggle: (bool val) {
                      isSwitchOn = val;
                  })

自定义开关小部件:

class Switch extends StatefulWidget {
 Widget build(BuildContext context) {
    return CupertinoSwitch(
        value: widget.value,
        onChanged: (bool value) {
          setState(() {
            widget.value = value;
          });
          widget.onSwitchToggle(value);
        },
),
}

每当我需要开关时,代码中的任何地方都会使用开关小部件,有时我不需要知道开关的状态,我只需要在开关切换时执行一个函数,但我的方式是写了代码,每当我调用开关时,我都需要到处传递布尔值。寻找更好的方法来做到这一点。 例如:Bool val 是不必要的,因为我不需要它。

Switch(onSwitchToggle: (bool val) {
                     print('abc')
                 })

【问题讨论】:

  • 您可以使用 GlobalKey()。并得到这样的状态。 this.globalkey.currentState.isSwitchOn
  • 拥有控制器的意义不在于我们不必使用 GlobalKey() 吗?
  • 你解决了这个问题吗,@suma?

标签: flutter dart controller toggleswitch


【解决方案1】:

您可以使用 ChangeNotifier 轻松解决它。其实TextFieldControllerScrollController也是这样解决的。

根据您的描述,我为您准备了一些示例代码:

class SwitchController extends ChangeNotifier {
  bool isSwitchOn = false;

  void setValue(bool value) {
    isSwitchOn = value;
    notifyListeners();
  }
}

现在你的小部件包装了 Switch:

class CustomSwitch extends StatefulWidget {
  CustomSwitch({
    required this.controller
  });

  final SwitchController controller;

  @override
  State<StatefulWidget> createState() {
    return _CustomSwitchState();
  }
}

class _CustomSwitchState extends State<CustomSwitch> {
  @override
  Widget build(BuildContext context) {
    return CupertinoSwitch(
      onChanged: (bool value) {
        widget.controller.setValue(value);
      },
      value: widget.controller.isSwitchOn,
    );
  }
}

只需监听原生开关的change事件,设置控制器的值即可。然后通知观察者。

然后您可以创建小部件并传递一个您添加侦听器的控制器:

class SwitchTest extends StatefulWidget {
  @override
  _SwitchTestState createState() => _SwitchTestState();
}

class _SwitchTestState extends State<SwitchTest> {
  SwitchController controller = SwitchController();

  @override
  void initState() {
    controller.addListener(() {
      setState(() {
        print(controller.isSwitchOn);
      });
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          children: [
            CustomSwitch(
              controller: controller
            ),
            Text(controller.isSwitchOn.toString()),
          ],
        ),
      ),
    );
  }
}

我已经在我的博客上写了一篇关于如何创建此类自定义控制器的详细教程:https://www.flutterclutter.dev/flutter/tutorials/create-a-controller-for-a-custom-widget/2021/2149/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-08
    • 2015-11-19
    • 1970-01-01
    • 2010-11-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多