Flutter: Working with callbacks

Avnish Nishad
2 min readOct 23, 2021

--

Ever tried to refract your code and find it difficult to call setState in parents widgets from the child widget. Then You’re in right place.

Today we will use flutter callbacks to call setState from child to parent widget.

VoidCallbacks

Functional Callbacks

Functional callback using typedef

  1. VoidCallbacks are functions that take no parameters and return no value. This can be useful when we only want to notify the parent widgets about an event that happened in the child Widget.
//ParentWidget
@override
Widget build(BuildContext context) {
return
ChildWidget(callback:()=> print("Button clicked"));
}
// children ButtonWidget

class ChildWidget extends StatelessWidget{
final VoidCallback callback;
const ChildWidget({Key key, @required this.callback}) : super(key:
key);

@override
Widget build(BuildContext context) {
return MaterialButton(
child: Text("Button"),
onPressed:()=>callback
);
}}

2. Functional callbacks are callbacks that notify the parent widget about an event that happened in the child widget and also return a value to the parent widget.

//parent widgetclass _MyWidgetState extends State<MyWidget> {
int _count=0;
@override
Widget build(BuildContext context) {
return Column(
mainAxisAlignment:MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [

Text(
"$_count",
style: Theme.of(context).textTheme.headline4,
),

ChildWidget(callback:(value)=> setState((){
_count+=value;
})),
],
);
}
}
//child widgetclass ChildWidget extends StatelessWidget{
final Function(int) callback;
const ChildWidget({Key key, @required this.callback}) : super(key:
key);

@override
Widget build(BuildContext context) {
return MaterialButton(
child: Text("Increment"),
onPressed:()=>callback(1)
);
}
}

3. Functional callback using typedef these types of callbacks are just another form of functional callback. We use the typedef keyword to give the alias name to the Functional callback datatype. I am including this in this blog because some tutorials are using typedef to teach callbacks and you can get confused when you first encounter this syntax.

// child widget
typedef void CallBackFunction(int);
class ChildWidget extends StatelessWidget{
final CallBackFunction callback;
const ChildWidget({Key key, @required this.callback}) : super(key:
key);

@override
Widget build(BuildContext context) {
return MaterialButton(
child: Text("Increment"),
onPressed:()=>callback(1)
);
}

Thank you, If you find this blog helpful then clap for me. Your Claps motivates me to write more valuable blogs for you and other developers.

Another way to do so is valueNotifier
https://medium.com/@avnishnishad/flutter-communication-between-widgets-using-valuenotifier-and-valuelistenablebuilder-b51ef627a58b

--

--