【问题标题】:Flutter scaffold of context giving "does not contain a Scaffold"上下文给出的颤振脚手架“不包含脚手架”
【发布时间】:2020-05-28 08:49:31
【问题描述】:

我在脚手架中有一个应用栏。

return Scaffold(
  appBar: styling.appBar(
      AppBar(
        leading: styling.iconButton(() => Scaffold.of(context).openDrawer(), Icons.menu),
      )
  ),
);

这是图标按钮:

  ClipRRect iconButton(VoidCallback onPressed, IconData icon) {
return ClipRRect(
  borderRadius: BorderRadius.circular(360),
  child : Material(
      color: Colors.transparent,
      child: IconButton(
        icon: Icon(
          icon,
          color: secondaryColor,
        ),
        onPressed: onPressed,
      )
  ),
);

}

这是替换打开抽屉的默认汉堡图标,当我点击它时,我得到这个错误:

Scaffold.of() called with a context that does not contain a Scaffold.

【问题讨论】:

  • 因为传递给您的build 方法的BuildContext 不包含Scaffold。尝试将您的主要小部件包装在 Builder 中。
  • 谢谢你,兄弟,你是我生命中的面包
  • @iaminpainpleasehelp1 - 下面详细介绍了完整的解释和可能的解决方法

标签: flutter


【解决方案1】:

编辑1:简单的解决方案

Builder(
  builder: (context) {
    return Scaffold(
      drawer: Drawer(),
      appBar: AppBar(
        leading: IconButton(
          icon: Icon(Icons.menu),
          onPressed: () => Scaffold.of(context).openDrawer(),
        ),
      ),
    );
  },
)

【讨论】:

  • 根据文档,api.flutter.dev/flutter/widgets/GlobalKey-class.html,全局键很昂贵。你应该谨慎使用它们。在这种情况下,可以通过使用成本低得多的 Builder 轻松解决问题。在这种情况下,全局键不是最好的解决方案,尽管有时它们是肯定的
  • @loushou,之前的替代方案很昂贵的事实与它是一个有效的答案无关。唯一值得注意的是您添加的内容。
  • @Storo 如果遵循 Flutter 团队、Flutter 框架的创建者和维护者概述的指南,对于有关 Flutter 框架的问题的正确答案没有相关性,那么您是对的......这没什么区别。但是,如果您想参与社区,并按照预期的方式使用技术,那么它是完全相关的。你的电话真的。接受建议或离开它。对我来说不重要。
【解决方案2】:

这几乎可以肯定是因为您的 context 实际上位于脚手架之外。您的函数可能类似于以下内容:

Widget build(BuildContext context) {
  // ... other code up here

  return Scaffold(
    appBar: styling.appBar(AppBar(
      leading: styling.iconButton(() => Scaffold.of(context).openDrawer(), Icons.menu),
    )),
  );
}

这里的问题是context 实际上确实来自一个不在脚手架内的地方。您在此处使用的 context 来自包装 build() 函数的函数参数,该函数确实存在于 Scaffold 之外(因为这个 build() 是实际生成 Scaffold 的原因)。

你需要做的是这样的:

Widget build(BuildContext context) {
  // ... other code up here

  return Scaffold(
    appBar: styling.appBar(
      AppBar(
        leading: Builder(
          builder: (BuildContext context) {
            return styling.iconButton(() => Scaffold.of(context).openDrawer(), Icons.menu);
          },
        ),
      ),
    ),
  );
}

或类似的东西。原因是现在,在 builder 函数中,您实际上有一个新的 context 对象,它实际上将存在于 Scaffold 中。

希望这很清楚。如果没有,我可以进一步解释。

【讨论】:

    猜你喜欢
    • 2021-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-02
    • 2019-10-06
    • 2020-03-03
    • 1970-01-01
    • 2023-01-13
    相关资源
    最近更新 更多