Home > database >  how can I call function with callback value from custom widget
how can I call function with callback value from custom widget

Time:09-13

I am using animated_toggle_switch package and I want to make it as widget. It provides onChange function with callback for selecting a new value. Is there anyway to call this onChange function with the callback value from another file?

File1.dart

import 'package:example/custom_animated_toggle_switch.dart'

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Custom_animated_toggle_switch(
     ...
     onChange: () => {
      //i want to do something here with the callback value
    }
  )
)

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_switch();
}

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()
    }),
   )
  }
}

CodePudding user response:

VoidCallback is for void function, which is we cant get any value changed from other class.

this is the solution

class Custom_animated_toggle_switch extends StatefulWidget {
  final ValueChanged<int> onChange;
  Custom_animated_toggle_switch({
   required this.onChange,
  }) : super(key: key);

......

 @override
  Widget build(BuildContext context) {
    return AnimatedToggleSwitch<int>.size(
      ...
      onChanged: (newValue)  {
      // here you pass newValue 

      widget.onChanged(newValue); // this newValue you can get on other class
    }     
   )
  }
}

and call it like usually onChanged function

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Custom_animated_toggle_switch(
     ...
    // onchange type value is int, because we initialize with ValueChanged<int>
     onChange: (int val) => {
     print(val);  // this value is newValue from your custom widget
    }
  )
)
  • Related