gpt4 book ai didi

flutter - 如何从另一个小部件中的某个按钮调用 StatefulWidget 中的函数?

转载 作者:行者123 更新时间:2023-12-03 03:57:47 26 4
gpt4 key购买 nike

如何调用movePage(page) Widget1中的函数来自 MaterialButton在小部件树中深深嵌套在下面?

请引用下面的示例代码:

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: () => {});
}
}

最佳答案

您可以将其传递给构造函数。试试这个 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'),
);
}
}

关于flutter - 如何从另一个小部件中的某个按钮调用 StatefulWidget 中的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59808717/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com