While looking for examples for using flutter `SnackBar` with `ScaffoldMessenger`, I only found usages with `onPressed` function:

```
    Widget build(BuildContext context) {
        return Container(
            child: ElevatedButton(
              child: ...,
              onPressed: () => _showToast(context),
            ));
      }

      void _showToast(BuildContext context) {
        final scaffold = ScaffoldMessenger.of(context);
        scaffold.showSnackBar(
          SnackBar(content: const Text('Added to favorite')),
        );
      }
    }

```

but non of the examples explain why one have to use it with onPressed only,
so I tried it my self and used in directly inside the build function:

```
         Widget build(BuildContext context) {
           _showToast(context);   <---
           return Container(
              child: ElevatedButton(
                ...,
            ));
      }

```

but than I got this error:

[![enter image description here](https://i.stack.imgur.com/HSQYo.png)](https://i.stack.imgur.com/HSQYo.png)

and I am not sure why this it happening.

I ended up giving Scaffold a key and using the `GlobalKey<ScaffoldState>` approach, but I really want to understand why using `ScaffoldMessenger.of(context).showSnackBar()` without a callback\onPressed didn't work