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

时间:2020-01-19 09:17:27

标签: flutter dart

如何从movePage(page)的{​​{1}}中调用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: () => {});
  }
}

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

我终于发现它可以使用bin了。

参考: Call method of a widget from another widget

代码在他的博客中: http://www.hellomonk.com/2018/03/communication-between-widgets-using.html

我会把它留在这里,以备不时之需。