You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何跨文件调用自定义AnimatedToggleSwitch带回调值的onChange方法

问题:自定义Toggle组件如何传递选中值给外部回调

我使用animated_toggle_switch包封装了自定义组件Custom_animated_toggle_switch,该组件底层的AnimatedToggleSwitch提供的onChanged回调会返回新选中的值。目前自定义组件的onChange为无参的VoidCallback,无法传递该值,我希望在另一个文件(File1.dart)中调用这个onChange时能获取到回调值并进行处理,请问该如何实现?

原始File1.dart代码

import 'package:example/custom_animated_toggle_switch.dart'

@override
Widget build(BuildContext context) {
  return Container(
    child: Custom_animated_toggle_switch(
      ...
      onChange: () => {
        // 希望在这里拿到回调值并处理
      }
    )
  );
}

原始custom_animated_toggle_switch.dart代码

class Custom_animated_toggle_switch extends StatefulWidget {
  ...
  VoidCallback onChange;

  Custom_animated_toggle_switch({
    ...
    this.onChange = void onChange() {},
  }) : super(key: key);

  @override
  State<Custom_animated_toggle_switch> createState() => _Custom_animated_toggle_switchState();
}

class _Custom_animated_toggle_switchState extends State<Custom_animated_toggle_switch> {
  @override
  Widget build(BuildContext context) {
    return AnimatedToggleSwitch<int>.size(
      ...
      onChanged: (newValue) => setState(() => {
        widget.onChange()
      }),
    );
  }
}

解决方案

要实现传递选中值,只需要将自定义组件的回调类型从无参的VoidCallback改为带参数的ValueChanged<T>(这里T对应底层返回的int类型),具体步骤如下:

1. 修改自定义组件(custom_animated_toggle_switch.dart)

将回调类型替换为ValueChanged<int>,并在底层onChanged中把选中值传递给外部回调:

class Custom_animated_toggle_switch extends StatefulWidget {
  ...
  // 替换VoidCallback为ValueChanged<int>,支持传递int类型的选中值
  final ValueChanged<int> onChange;

  Custom_animated_toggle_switch({
    ...
    // 设置默认空回调,避免未传入时报错
    this.onChange = (value) {},
  }) : super(key: key);

  @override
  State<Custom_animated_toggle_switch> createState() => _Custom_animated_toggle_switchState();
}

class _Custom_animated_toggle_switchState extends State<Custom_animated_toggle_switch> {
  @override
  Widget build(BuildContext context) {
    return AnimatedToggleSwitch<int>.size(
      ...
      onChanged: (newValue) {
        setState(() {}); // 如果需要更新组件内部状态则保留,不需要可移除
        // 将底层返回的newValue传递给外部回调
        widget.onChange(newValue);
      },
    );
  }
}

2. 在File1.dart中接收并处理回调值

现在可以直接在onChange中拿到选中的int值,进行业务处理:

import 'package:example/custom_animated_toggle_switch.dart'

@override
Widget build(BuildContext context) {
  return Container(
    child: Custom_animated_toggle_switch(
      ...
      onChange: (newValue) {
        // 这里拿到选中的newValue,做你需要的处理
        print('当前选中值:$newValue');
        // 比如更新本地状态、发起网络请求等
      }
    )
  );
}

内容的提问来源于stack exchange,提问作者hanzanman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 19:20:29