使用GlobalKey来获取StatefulWidgets的状态并在异步操作中传递状态。
以下是一个简单的示例:首先,我们创建一个包含按钮的StatefulWidget,并使用一个GlobalKey来获取其状态:
class MyButton extends StatefulWidget {
const MyButton({ Key key }) : super(key: key);
@override
_MyButtonState createState() => _MyButtonState();
}
class _MyButtonState extends State {
bool _isLoading = false;
void setLoading(bool value) {
setState(() {
_isLoading = value;
});
}
@override
Widget build(BuildContext context) {
return RaisedButton(
onPressed: _isLoading ? null : _handlePressed,
child: _isLoading ? const CircularProgressIndicator() : const Text('Press Me'),
);
}
void _handlePressed() async {
final key = GlobalKey<_MyButtonState>();
key.currentState.setLoading(true);
await Future.delayed(const Duration(seconds: 2));
key.currentState.setLoading(false);
}
}
在这个例子中,当按钮被按下时,我们使用一个GlobalKey来获取按钮的当前状态,并将按钮的状态传递给异步操作。在异步操作结束后,我们再次使用GlobalKey来获取按钮的状态并更新按钮。
这是一种解决BuildContext跨异步间隙的问题的方法,它使用了GlobalKey来获取StatefulWidgets的状态。