You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter导航代码中三处context的含义分别是什么?

Flutter导航代码中多处context的含义解析

先看你给出的完整代码:

Navigator.push(context, MaterialPageRoute<void>(
  builder: (BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('My Page')),
      body: Center(
        child: TextButton(
          child: Text('POP'),
          onPressed: () {
            Navigator.pop(context);
          },
        ),
      ),
    );
  },
));

下面逐个解释每一处context的含义:

  • 第一处Navigator.push(context, ...)中的context:
    这是发起导航的当前页面的BuildContext,对应你当前页面Widget树里的一个节点。Flutter的Navigator需要通过这个context向上查找,找到当前活跃的导航栈(NavigatorState),才能把新页面推入栈中。

  • 第二处builder: (BuildContext context) { ... }中的context:
    这是新页面的BuildContext,属于即将创建的新页面Widget树的节点,和第一处的context完全是不同的层级。这个context是MaterialPageRoute构建新页面时传入的,用来关联新页面里的Scaffold、TextButton等Widget,方便新页面内部获取自身的Widget树信息。

  • 第三处Navigator.pop(context);中的context:
    这就是builder参数里的新页面context,Navigator通过它找到新页面所在的导航栈,执行pop操作把当前新页面从栈中移除,回到上一个页面。

内容的提问来源于stack exchange,提问作者baha zou

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 05:20:28