BuildContext

이원석·2023년 11월 13일
0

Flutter

목록 보기
12/46

BuildContext

BuildContext란 위젯 트리에서 위젯의 위치를 다루는 것

Flutter안에 모든 Widget은 내부에 bulid method를 가지고 있다.
그리고 그 build method의 타입은 Widget이고 인자 값으로 BuildContext를 가진다.
bulid method는 구현한 UI위젯들을 화면에 출력될 수있도록 리턴해준다

BuildContext 타입은 현재 위젯의 위젯트리상에서 위치에 관한 정보를 담고 있다.

class MyHomePage extends StatelessWidget {
  const MyHomePage({ Key? key }) : super(key: key);

  
	// 여기서 context는 이 MyHomePage를 부르는 부모위젯의 위치정보를 담고 있음
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar( title: Text("MyHomePage"), ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            const Text('Test', ),
          ],
        ),
      ),
    );
  }
}

Context를 다루면서 자주하는 실수

of 함수를 다룰때

현재 위젯과 가장 가까운 어떠한 위젯을 찾을때 보통 of 함수를 많이 사용

class MyHomePage extends StatelessWidget {
  const MyHomePage({ Key? key }) : super(key: key);

  
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar( title: Text("MyHomePage"), ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            ElevatedButton(
              onPressed: (){
                Scaffold.of(context).showSnackBar(SnackBar(content: Text('snack bar')));
              },
              child: Text('button'),
            ),
          ],
        ),
      ),
    );
  }
}

이떄, 위 코드에서 Scaffold.of하수는 인자로 제공해준 context에서 조상중 가장 가까운 Scaffold를 반환해 주는 역할을 한다. 하지만 저 context는 MyHomePage를 호출하는 부모의 위치가 담겨져있다. 즉 현재 Scaffold보다 부모에 존재하는 Scaffold를 찾게 된다.

해결방법

  • Builder이용하여 Scaffold아래에 새로운 context 생성
class MyHomePage extends StatelessWidget {
  const MyHomePage({ Key? key }) : super(key: key);

  
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar( title: Text("MyHomePage"), ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Builder(builder: (ctx) {
              return ElevatedButton(
                onPressed: (){
                  Scaffold.of(ctx).showSnackBar(SnackBar(content: Text('snack bar')));
                },
                child: Text('button'),
              );
            })
          ],
        ),
      ),
    );
  }
}
  • 새로운 widget class로 만들어주기
class MyHomePage extends StatelessWidget {
  const MyHomePage({ Key? key }) : super(key: key);

  
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar( title: Text("MyHomePage"), ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            MyButton(),
          ],
        ),
      ),
    );
  }
}

class MyButton extends StatelessWidget {
  const MyButton({Key? key}) : super(key: key);

  
  Widget build(BuildContext context) {
    return ElevatedButton(
      onPressed: (){
        Scaffold.of(context).showSnackBar(SnackBar(content: Text('snack bar')));
      },
      child: Text('button'),
    );
  }

참조
로건

0개의 댓글