BuildContext
BuildContext 实际上是 Element 对象。BuildContext 接口用于阻止对 Element 对象的直接操作。
我们日常开发中,一般接触的都是 Widget,并没有使用到 Element,其实我们也在一直操作着 Element,BuildContext 对象实际上就是 Element 对象, Element 实现了 BuildContext,告诉了使用者控件在哪里、可以做什么。BuildContext 接口设计用于阻止对 Element 对象的直接操作。
通过navigatorKey的方式
void main() {
runApp(MyApp());
}
final GlobalKey<NavigatorState> navigatorKey = new GlobalKey<NavigatorState>();
class MyApp extends StatelessWidget {
MyApp() {
}
// This widget is the view.common.root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
navigatorKey: navigatorKey,
);
}
}
获取context:
Context context = navigatorKey.currentState.overlay.context
注意:通过这种方式获取的context在某些情况下(使用Overlays(比如Dialog)、MediaQuery等)需要在如下代码里面使用如:
/// 跳转到登录界面 全局context
Future.delayed(const Duration(microseconds: 0),(){
NavigatorUtils.push(
navigatorKey.currentState.overlay.context, LoginRouter.loginPage);
});