skip to Main Content

I am creating a custom widget of slider widget where there is a function of onChange

I dont know how to pass this function to a custom widget as it has argument

its easy to pass when a function is without argument

like

final VoidCallBack ontap;

class CustomSlider extends StatelessWidget {
  final double value;
// how to pass voidcallback with argument here
  const CustomSlider({Key? key,required this.value}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return SfSlider.vertical(
      min: 50,
      max: 250.0,
      value: value,
      interval: 20,
      showTicks: true,
      showLabels: true,
      enableTooltip: true,
      minorTicksPerInterval: 1,
      onChanged: (dynamic value) {
// how to deal with this function
      },
    );

  }
}

2

Answers


  1. final ValueSetter<int> onChanged; 
    //typedef ValueSetter<in T> = void Function(T value)
    

    OR

    final void Function(int) onChanged;
    

    if need back value:

    final String Function(int) onChanged;
    
    Login or Signup to reply.
  2. To pass a function with arguments to a custom widget in Flutter, you can define a function type as a parameter in your custom widget.

    In your case, since the onChanged function takes a dynamic value as an argument and returns void, you can define it as follows in your CustomSlider widget:

    typedef ValueChanged<T> = void Function(T value);
    
    class CustomSlider extends StatelessWidget {
      final double value;
      final ValueChanged<dynamic>? onChanged;
    
      const CustomSlider({
        Key? key,
        required this.value,
        this.onChanged,
      }) : super(key: key);
    
      @override
      Widget build(BuildContext context) {
        return Slider(
          value: value,
          min: 50,
          max: 250.0,
          onChanged: (newValue) {
            if (onChanged != null) {
              onChanged!(newValue);
            }
          },
        );
      }
    }
    

    Now, when you use CustomSlider, you can pass a function to the onChanged parameter:

    CustomSlider(
      value: _sliderValue,
      onChanged: (newValue) {
        setState(() {
          _sliderValue = newValue;
        });
      },
    )
    

    In this example, _sliderValue is a state variable that gets updated whenever the slider value changes. The setState call ensures that the widget rebuilds with the new slider value. Note that you may want to make sure that the function you pass to onChanged expects a parameter of the type that the Slider will emit (probably a double in this case).

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search