[Flutter] SnackBar Scaffold error

쏘리초이·2021년 4월 7일
0
post-thumbnail

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

No Scaffold ancestor could be found starting from the context that was passed to Scaffold.of(). This usually happens when the context provided is from the same StatefulWidget as that whose build function actually creates the Scaffold widget being sought.
There are several ways to avoid this problem. The simplest is to use a Builder to get a context that is "under" the Scaffold. For an example of this, please see the documentation for Scaffold.of():
  https://api.flutter.dev/flutter/material/Scaffold/of.html
A more efficient solution is to split your build function into several widgets. This introduces a new context from which you can obtain the Scaffold. In this solution, you would have an outer widget that creates the Scaffold populated by instances of your new inner widgets, and then in these inner widgets you would use Scaffold.of().
A less elegant but more expedient solutio<>

이 에러가 발생한 이유는, 해당 context가 scaffold가 있는 context가 아니라는 이슈이다.

따라서 globalKey값으로 scaffold의 context를 전달해줌으로써 해결이 가능하다.

☠️ 에러 발생한 코드

...
@override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(child:Text('Scaffold Error')),
      floatActionButton: FloatActionButton(
        onTap: _showSanckBar,
      ),
    );
...
 void _showSnackBar() {
    SnackBar snackBar = SnackBar(
      content: Text('Scaffold Error!!'),
      action: SnackBarAction(
        label: 'OK',
        onPressed: () {
          Scaffold.of(context).hideCurrentSnackBar();
        },
      ),
    );
    Scaffold.of(context).showSnackBar(snackBar);
  }

✅ 해결방법

...
GlobalKey<ScaffoldState> _key = GlobalKey<ScaffoldState>();

@override
  Widget build(BuildContext context) {
    return Scaffold(
      key: _key,
      body: Container(child:Text('Scaffold Error solved')),
      floatActionButton: FloatActionButton(
        onTap: _showSanckBar,
      ),
    );
...
void _showSnackBar() {
    SnackBar snackBar = SnackBar(
      content: Text('Scaffold Error solved!!'),
      action: SnackBarAction(
        label: 'OK',
        onPressed: () {
          _key.currentState.hideCurrentSnackBar();
        },
      ),
    );
    _key.currentState.showSnackBar(snackBar);
  }

GlobalKey값을 가지고 해결할 수 있다!

profile
Hello Universe!

0개의 댓글