Updated 28 October 2024
Hello, Flutter devs! Today, let’s dive into callbacks through ValueChanged to boost interactivity in your Flutter apps. Let’s go!
Before we explore callbacks, it’s essential to grasp the basics of Flutter and Dart.
ValueChnaged in Flutter applies to various scenarios, so you should have at least a basic knowledge of classes (Stateful/Stateless), functions, and generic parameters.
Now, let’s dive deeper into what ValueChanged is and how it works in practice!
The ValueChanges is a signature for callbacks that report that an underlying value has changed.
In other words, ValueChanged is a function signature that takes a single generic type argument of type T and doesn’t return anything (void).
1 |
typedef ValueChanged<T> = void Function(T value); |
ValueChanged notifies the app of value changes. It appears in input widgets, capturing user actions like typing, selecting from a dropdown, or adjusting a slider.
ValueChanged
Used?ValueChanged captures non-null user input with a generic return type. It’s widely used in widgets like TextField, Slider, and Switch to respond to interactions and update the UI.
Although we can perform the same task with a Function as a callback, using callbacks through ValueChanged offers better clarity and type safety, making the code more readable and easier to maintain.
Let’s create a class that performs actions and sends a response each time an action occurs.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
class CustomSliderClass extends StatelessWidget { final double value; final ValueChanged<double> onChanged; MySlider({required this.value, required this.onChanged}); @override Widget build(BuildContext context) { return Slider( value: value, min: 0, max: 100, onChanged: onChanged, // Use the ValueChanged callback ); } } |
As we can see, the above CustomSliderClass has an onChanged ValueChnaged and is working as a callback to return the data from onChanged of the Slider class.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
class MyWidget extends StatefulWidget { @override _MyWidgetState createState() => _MyWidgetState(); } class _MyWidgetState extends State<MyWidget> { double _sliderValue = 50; @override Widget build(BuildContext context) { return Column( children: [ CustomSliderClass( value: _sliderValue, onChanged: (newValue) { setState(() { _sliderValue = newValue; }); }, ), Text('Slider Value: $_sliderValue'), ], ); } } |
In Flutter, both Function and ValueChanged work as callbacks, each with unique advantages based on project context. Here’s an overview of their differences:
In conclusion, ValueChanged
provides a clear, type-safe way to handle single-value changes in Flutter, enhancing code readability and consistency.
Discover more insightful Flutter content and make your development journey even more fruitful with Mobikul Blogs. Happy coding!
If you have more details or questions, you can reply to the received confirmation email.
Back to Home
Be the first to comment.