简体   繁体   中英

Flutter scaffold of context giving "does not contain a Scaffold"

I have an appbar in a scaffold.

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

This is the 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,
      )
  ),
);

}

This is to replace the default hamburger icon that opens the drawer, when I click it I get this error:

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

This almost certainly because your context is ACTUALLY outside of a Scaffold. Your function probably looks something similar to this:

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

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

The problem here is that context actually DID come from a place that is not inside the Scaffold. The context that you are using here is from the function parameter of the wrapping build() function, which does exist outside of the Scaffold (because this build() is what is actually generating the Scaffold ).

What you need to do is something like this:

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);
          },
        ),
      ),
    ),
  );
}

Or something similar. The reason is because now, inside the builder function, you actually have a new context object, which WILL actually exist inside the Scaffold.

Hopefully that is clear. If not, I can explain further.

Edit 1: simple solution

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM