Created
October 6, 2019 20:18
-
-
Save jehadnasser/b3a841ed84ab8b7704ba5b358c29524b to your computer and use it in GitHub Desktop.
Steps to create a callback from child to parent widget
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// | |
/// Inside the Child Widget | |
/// | |
import 'package:flutter/material.dart'; | |
// Step 1: Define a Callback. | |
typedef void IntCallback(int id); | |
class Son extends StatelessWidget { | |
// Step 2: Configre the child to expect a callback in the constructor(next 2 lines): | |
final IntCallback onSonChanged; | |
Son({ @required this.onSonChanged }); | |
int elementId = 3; | |
@override | |
Widget build(BuildContext context) { | |
return RaisedButton( | |
onPressed: () { | |
// Step 3: On specific action(e.g onPressed/ | |
// onTap/onLoad.. onWhatEver) trigger the callback | |
// with the data you want to pass to the parent. | |
// Data will be passed as parameter(see elementId): | |
onSonChanged(elementId); | |
// Done in the child. | |
}, | |
child: Text('Click me to call the callback!'), | |
), | |
} | |
} | |
/// | |
/////////////// | |
/// | |
/// Inside the Parent Widget | |
/// | |
import 'package:flutter/material.dart'; | |
class Father extends StatefulWidget { | |
@override | |
_FatherState createState() => _FatherState(); | |
} | |
class _FatherState extends State<Father> { | |
// Step 1 (optional): Define a Global variable | |
// to store the data comming back from the child. | |
int id; | |
// Step 2: Define a function with the same signature | |
// as the callback, so the callback will point to it, | |
// this new function will get the data from the child, | |
// set it to the global variable (from step 1) | |
// in the parent, and then update the UI by setState((){}); | |
void updateId(int newId) { | |
setState(() { | |
id = newId; | |
}); | |
} | |
@override | |
Widget build(BuildContext context) { | |
return Container( | |
// Step 3: Construct a child widget and pass the | |
child: Son( | |
// Many options to make onSonChanged points to | |
// an executable code(function) within memory | |
// called 'updateId': | |
// | |
// 1st option: | |
onSonChanged: (int newId) { | |
updateId(newId) | |
}, | |
// 2nd option: onSonChanged: updateId, | |
// 3rd option: onSonChanged: (int newId) => updateId(newId) | |
// So each time the 'onSonChanged' called by the action | |
// we defined inside the child, a new data will be | |
// passed to this parent. | |
) | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment