Flutter | Widget Communication With Callbacks (Flutter 3 , Dart 2.17)
Table of contents:
- What is this callback and why we should use to it?
- Making a custom button with callback which can react a future calls and show loading progress to us.
- Return a value from callback
- Pass a value to widget via callback
What is callback ?
Callbacks are functions or methods which we can pass an argument or make them as void type and call from another methods or widgets if as needed. For example this guy ,
typedef VoidCallback = void Function();
This guy is built-in callback signature from Flutter framework.
Do I have to use callbacks for widgets communication?
No , there are many ways to do this. You can use any state management libraries or create a static instances which can be mutable from widgets. But callbacks are simple and simplicity is good in my opinion :).
So now, let’s make a custom button which can be show loading indicator inside through callback event.
We made _CustomFutureButton as stateful widget because we want to change _isLoading value according to given callbacks. You can see onPressed callback declaration in class like this:
final Future<void> Function() onPressed;
We can use Voidcallback for onPressed event offcourse but we want to show loading indicator according to given Future process. Therefore we declare return type as Future. If you call this widget and send a Future method in onPressed callback you can see loading indicator instead of Text widget until Future completed. You can get the entire code at the end of the article.
So , If I need a value from a widget , can I get this from callback?
Let’s see:
We create a _BatteryButton class for this example. This class has a getBatteryInfo callback which return a device battery level as double value. If we call this function as below like this,
Center(child:_BatteryButton(
getBatteryInfo: (double? level) {
print(level);
},
),
)
You can see double value in debug console , so we can get a value from callback :).
Okey last one , how can I pass a value to widget itself with given callback by widget?
Okay , we are going to make pleasant example now.
We create a three filter chip and a animated clickable container. When we press container animation will play. When animation is completed , selected chip color will apply to container color via callback function. I am not going to show boilerplate code , already you can access rest of them end of the article.
Here is our container:
Okay , you can see callback function at line 7. It has a return type as Color. So whoever call this, they should return a Color or a null. Like this :
So , we are done 🥳. You can find rest of code in my github. Even would be find more if you want 😁. Happy coding !.