Flutter中的上下文提供的scaffold出现“不包含Scaffold”问题

5
我在一个 scaffold 中有一个 appbar。
return Scaffold(
  appBar: styling.appBar(
      AppBar(
        leading: styling.iconButton(() => Scaffold.of(context).openDrawer(), Icons.menu),
      )
  ),
);

这是iconButton:
  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 - Ryosuke
谢谢兄弟,你是我生命中的面包。 - iaminpainpleasehelp1
@iaminpainpleasehelp1 - 下面详细解释了问题并提供了可能的解决方法。 - loushou
2个回答

12
这几乎肯定是因为你的context实际上在Scaffold之外。你的函数可能看起来类似于这样:

这几乎可以确定是因为你的context实际上不在Scaffold之内。你的函数可能看起来类似于这样:

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

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

问题在于context实际上来自于一个不在 Scaffold 内部的地方。你在这里使用的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内。

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


-1

编辑1:简单解决方案

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

根据文档 https://api.flutter.dev/flutter/widgets/GlobalKey-class.html,全局键是昂贵的。你应该谨慎使用它们。在这种情况下,可以通过使用 Builder 轻松解决问题,这要便宜得多。在这种情况下,全局键不是最好的解决方案,尽管有时候它们确实是。 - loushou
@loushou,之前的替代方案昂贵与其是否有效并无关系。值得注意的是你所添加的内容。 - Storo
@Storo,如果你按照Flutter框架的创建者和维护者制定的指南行事,对一个关于Flutter框架的问题没有任何影响,那么你是正确的... 它没有任何区别。但是,如果你想参与社区,并按照既定方式使用技术,那么这完全相关。真的取决于你。接受建议或不接受都无所谓,对我来说没关系。 - loushou

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接