[英]How to call function in a StatefulWidget from a button somewhere within another widget?
How do I call the movePage(page)
function in Widget1
from MaterialButton
that placed deeply nested down below within the widget tree?我如何从
MaterialButton
中调用movePage(page)
函数, Widget1
函数在小部件树的下方嵌套Widget1
深?
Please refer to example code below:请参考下面的示例代码:
class Widget1 extends StatefulWidget {
@override
_Widget1State createState() => _Widget1State();
}
class _Widget1State extends State<Widget1> {
int _selectedIndex = 0;
void movePage(page) {
setState(() {
_selectedIndex = page;
});
}
@override
Widget build(BuildContext context) {
return Container();
}
}
///Somewhere nested down below within another widget in the widget tree
class Widget12 extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialButton(onPressed: () => {});
}
}
You could just pass it to the constructor.你可以把它传递给构造函数。 Try this on DartPad .
在DartPad上试试这个。
class Widget1 extends StatefulWidget {
@override
_Widget1State createState() => _Widget1State();
}
class _Widget1State extends State<Widget1> {
int _selectedIndex = 0;
void movePage(int page) => setState(() => _selectedIndex += page);
@override
Widget build(BuildContext context) {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text('$_selectedIndex'),
Widget2(func: movePage),
],
);
}
}
class Widget2 extends StatelessWidget {
final void Function(int) func;
const Widget2({Key key, @required this.func}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialButton(
/// Try with any number.
onPressed: () => func(2),
child: Text('button'),
);
}
}
I finally find it working using InheritedWidget
.我终于发现它使用
InheritedWidget
工作。
Reference: Call method of a widget from another widget参考: 从另一个小部件调用小部件的方法
The codes are in his blog: http://www.hellomonk.com/2018/03/communication-between-widgets-using.html代码在他的博客中: http : //www.hellomonk.com/2018/03/communication-between-widgets-using.html
I will just leave it here for who might need it as well.我会把它留在这里给可能需要它的人。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.