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

点击图标时触发错误,请求排查Flutter(Dart)代码问题

点击图标触发错误的解决方案

点击AppBar上的添加图标时会触发错误,相关Dart代码片段如下:

return Scaffold(
      backgroundColor:
          width > webScreenSize ? webBackgroundColor : Colors.white,
      appBar: width > webScreenSize
          ? null
          : AppBar(
              backgroundColor: mobileBackgroundColor,
              centerTitle: false,
              title: SvgPicture.network(
                '',
                color: primaryColor,
                height: 40,
              ),
              actions: [
                  Center(
                    child: Row(children: [
                      IconButton(
                        icon: const Icon(
                          Icons.add_box_outlined,
                          color: primaryColor,
                        ),
                        onPressed: () => Navigator.of(context).push(
                          MaterialPageRoute(
                            builder: (context) => const AddPostScreen(),
                          ),
                        ),
                      ),
                    ]),
                  ),
                ]),

根据报错信息(原截图显示Navigator operation requested with a context that does not include a Navigator),结合代码分析,问题出在以下几点:

  • 调用Navigator.of(context)时使用的是Scaffold父级的上下文,该上下文未包含Navigator实例
  • actions中多余的Center和Row嵌套不仅没必要,还可能干扰上下文传递
  • SvgPicture.network('')的空URL会触发资源加载错误,影响页面稳定性

修复方案

修改后的代码如下:

return Scaffold(
  backgroundColor: width > webScreenSize ? webBackgroundColor : Colors.white,
  appBar: width > webScreenSize
      ? null
      : AppBar(
          backgroundColor: mobileBackgroundColor,
          centerTitle: false,
          title: SvgPicture.network(
            // 替换为你的有效SVG图标URL
            'https://your-icon-url.svg',
            color: primaryColor,
            height: 40,
          ),
          actions: [
            Builder(
              builder: (context) => IconButton(
                icon: const Icon(
                  Icons.add_box_outlined,
                  color: primaryColor,
                ),
                onPressed: () => Navigator.of(context).push(
                  MaterialPageRoute(
                    builder: (context) => const AddPostScreen(),
                  ),
                ),
              ),
            ),
          ],
        ),
  // 补充Scaffold的其他内容
);

修改说明

  1. 获取正确上下文:用Builder包裹IconButton,获取Scaffold子树内的上下文,确保能找到Navigator实例
  2. 简化布局结构:移除actions中冗余的Center和Row,直接将IconButton加入列表,减少层级干扰
  3. 修复资源路径:替换空的SVG网络URL为有效地址,避免加载错误

内容的提问来源于stack exchange,提问作者Aditya Jain

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 01:12:56