[Flutter][에러] scaffold.of() called with a context that does not contain a scaffold

uengmin·2024년 4월 22일

Flutter

목록 보기
3/20

발생 이유

  • 오류가 발생하는 context가 코드 상의 scaffold가 있는 context가 아니기 때문에 발생.
  • widget tree 내에서 scaffold가 어디에 위치하고 있는지에 대한 정보를 가지고 있지 않음.

  • 두가지 방안으로 해결 가능함.

해결방안

1) 빌더 위젯 사용하기

Scaffold(
    appBar: AppBar(
        title: Text('My Profile'),
    ),
    body: Builder(
        builder: (ctx) => RaisedButton(
            textColor: Colors.red,
            child: Text('Submit'),
            onPressed: () {
            	ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
              		content: Text('Hello'),
            	));
            }               
        ),
    ),
);

- ScaffoldMessenger.of(context) method : 현재 주어진 context에서 위로 올라가면서 가장 가까운 Scaffold를 찾아서 반환하라.


2) 글로벌 키 사용하기

class HomePage extends StatelessWidget {
  
  final globalKey = GlobalKey<ScaffoldState>();
  
  
  Widget build(BuildContext context) {
     return Scaffold(
       key: globalKey,
       appBar: AppBar(
          title: Text('My Profile'),
       ),
       body:  RaisedButton(
          textColor: Colors.red,
          child: Text('제출'),
          onPressed: (){
               final snackBar = SnackBar(content: Text('Profile saved'));
               globalKey.currentState.showSnackBar(snackBar);
          },
        ),
     );
   }
}

0개의 댓글