How to Pass Data from Child Widget to Its Parent in Flutter
In order to pass data from children to its parent, we often use a callback. In Flutter, we define a callback using typedef. A typedef is a type alias. It is a shortcut for creating a new type based on an existing type.
However, in this post, we will use Notification. A notification is a message that can be broadcast to other widgets without using a callback. It is often used for communicating between parent and child widgets. Notification is also useful when we want to communicate between two unrelated widgets.
//define a notification
class ScanResultChanged extends Notification {
final bool correct;
final String message;
ScanResultChanged(this.correct, this.message);
}
//call it in an event of child widget
onPressed:(){
ScanResultChanged(true, "Scanned completed").dispatch(context);
}
//wrap the parent widget with NotificationListener<ScanResultChanged>
NotificationListener<ScanResultChanged>(
onNotification: (n) {
setState(() {
_scanCorrect = n.correct;
_scanMessage = n.message;
});
return true;
},
child: Container(
width: MediaQuery.of(context).size.width,
constraints: const BoxConstraints(minHeight: 36),
padding: const EdgeInsets.all(MyTheme.padding),
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
if(_scanCorrect)
Text(_scanMessage)
],
),
),
)