![](/img/trans.png)
[英]Scaffold.of() called with a context that does not contain a Scaffold
[英]Flutter scaffold of context giving "does not contain a Scaffold"
我在脚手架上有一个 appbar。
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.
这几乎可以肯定,因为您的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
实际上 DID 来自不在 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:简单的解决方案
Builder(
builder: (context) {
return Scaffold(
drawer: Drawer(),
appBar: AppBar(
leading: IconButton(
icon: Icon(Icons.menu),
onPressed: () => Scaffold.of(context).openDrawer(),
),
),
);
},
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.