Created
January 12, 2022 19:43
-
-
Save MCarlomagno/d005e773f631514121c4ebcc2148a0b1 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
import 'package:flutter/material.dart'; | |
class ParentWidget extends StatefulWidget { | |
const ParentWidget({Key? key}) : super(key: key); | |
@override | |
_ParentWidgetState createState() => _ParentWidgetState(); | |
} | |
class _ParentWidgetState extends State<ParentWidget> { | |
_updateStateFunction() { | |
setState(() { | |
// You can update whatever | |
// variable you want here | |
// and the build method will be called | |
}); | |
} | |
@override | |
Widget build(BuildContext context) { | |
return Scaffold( | |
body: Center( | |
child: ButtonWidget( | |
// this callback injection allows the | |
// child call the parent setState() function | |
// which is not recommended but possible | |
setParentState: _updateStateFunction, | |
), | |
), | |
); | |
} | |
} | |
class ButtonWidget extends StatelessWidget { | |
final Function()? setParentState; | |
const ButtonWidget({ | |
Key? key, | |
required this.setParentState, | |
}) : super(key: key); | |
@override | |
Widget build(BuildContext context) { | |
return MaterialButton( | |
height: 50, | |
// After pressing the button, | |
// the parent's setState method | |
// is called | |
onPressed: setParentState, | |
child: Text('My Button'), | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment