gpt4 book ai didi

flutter - 如何将 Controller 添加到 flutter 中的自定义小部件

转载 作者:行者123 更新时间:2023-12-04 13:40:08 26 4
gpt4 key购买 nike

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

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

父小部件:

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 。寻找更好的方法来做到这一点。
例如: Bool val 是不必要的,因为我不需要它。
Switch(onSwitchToggle: (bool val) {
print('abc')
})

最佳答案

您可以使用 ChangeNotifier 轻松解决它。这实际上也是它在 TextFieldController 中解决的方式和 ScrollController .
我根据您的描述为您提供了一些示例代码:

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,
);
}
}
只需监听 native 开关的更改事件并设置 Controller 的值即可。然后通知观察者。
然后您可以创建小部件并传递您添加监听器的 Controller :
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()),
],
),
),
);
}
}
我在我的博客上写了一篇关于如何创建此类自定义 Controller 的详细教程: https://www.flutterclutter.dev/flutter/tutorials/create-a-controller-for-a-custom-widget/2021/2149/

关于flutter - 如何将 Controller 添加到 flutter 中的自定义小部件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58367950/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com