1,通過GlobalKey獲取到state
在Scaffold中設(shè)置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對應(yīng)的ScaffoldState對象
如果使用是在StatelessWidget中,則可以直接獲取到widget上下文的content垄琐,直接使用context.findAncestorStateOfType獲取到state
ScaffoldState _state =
context.findAncestorStateOfType<ScaffoldState>();
如果需要在StatefulWidget 的 State中使用呢赠制?如何獲取到widget中的state?
此時(shí)可以通過Builder來構(gòu)建widget挟憔,Builder會將widget節(jié)點(diǎn)的context作為回調(diào)參數(shù)
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'),
);
}),