Flutter:获取状态state的几种方式

2021-01-26  本文已影响0人  xh_0129

1,通过GlobalKey获取到state

在Scaffold中设置key为GlobalKey,然后在使用的地方通过GlobalKey获取

class StatefullDemo extends StatelessWidget {
  static GlobalKey<ScaffoldState> _globalKey = GlobalKey();
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      key: _globalKey,
  ......
  ......
  ScaffoldState _state = _globalKey.currentState;

2,通过查找父级最近的Scaffold对应的ScaffoldState对象

如果使用是在StatelessWidget中,则可以直接获取到widget上下文的content,直接使用context.findAncestorStateOfType获取到state

ScaffoldState _state =
                  context.findAncestorStateOfType<ScaffoldState>();

如果需要在StatefulWidget 的 State中使用呢?如何获取到widget中的state?
此时可以通过Builder来构建widget,Builder会将widget节点的context作为回调参数

Builder(builder: (context) {
              return RaisedButton(
                onPressed: () {
                  ScaffoldState _state = context.findAncestorStateOfType();
                  SnackBar snackBar = SnackBar(content: Text('RaisedButton'));
                  _state.showSnackBar(snackBar);

                  ScaffoldState _state1 = this as ScaffoldState;
                },
                child: Text('RaisedButton'),
              );
            }),
上一篇下一篇

猜你喜欢

热点阅读