Let's say we have two stateful widgets.
ParentWidget(){
}
ChildWidget() {
someMethod(){
// some code, for example setState code
}
}
Now when I use the ChildWidget
in ParentWidget
, how do I call the someMethod()
?
CodePudding user response:
Here is way what I've used.
- Make a GlobalKey instance
- Pass the Globalkey as a Key parameter to child widget.
- Call GlobalKey.currentState.method();
GlobalKey<ChildWidgetState> globalKey = GlobalKey();
ParentWidget(){
ChildWidget(key: globalKey);
...
globalKey.currentState.someMethod();
}
ChildWidget() {
ChildWidget({Key key}) : super(key: key);
someMethod(){
// some code, for example setState code
}
}
TestCode
import 'package:flutter/material.dart';
const Color darkBlue = Color.fromARGB(255, 18, 32, 47);
void main() {
runApp(MyApp());
}
GlobalKey<ChildWidgetState> globalKey = GlobalKey();
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData.dark().copyWith(
scaffoldBackgroundColor: darkBlue,
),
debugShowCheckedModeBanner: false,
home: Scaffold(
body: Center(
child: MyWidget(),
),
),
);
}
}
class MyWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Column(
children: [
InkWell(
onTap: () {
globalKey.currentState.someMethod();
},
child: Text('ParentWidget'),
),
ChildWidget(key: globalKey),
],
);
}
}
class ChildWidget extends StatefulWidget {
ChildWidget({Key key}) : super(key: key);
@override
ChildWidgetState createState() => ChildWidgetState();
}
class ChildWidgetState extends State<ChildWidget> {
void someMethod() {
print('someMethod is called');
}
@override
Widget build(BuildContext context) {
return Text('childWidget');
}
}
edit: this approach works, but thanks @Andrija for pointing this out:
Just wanted to note - even though the answers below are good - you should not be doing this in the first place. This is an anti-pattern in flutter.
CodePudding user response:
If you need call function on widget you can use:
context.findAncestorWidgetOfExactType<T>()
If you need call function on state of that widget you can use:
context.findRootAncestorStateOfType<T>();
read more at:
https://api.flutter.dev/flutter/widgets/BuildContext/findAncestorWidgetOfExactType.html
https://api.flutter.dev/flutter/widgets/BuildContext/findRootAncestorStateOfType.html