22.새로 알게된 Flutter 지식 정리(02/07)

Chocomilk·2022년 2월 7일
0

1. Builder 클래스

1) 공식문서 정의

A stateless utility widget whose build method uses its builder callback to create the widget's child.
즉, Builder 콜백을 통해 StatelessWidget을 만드는 클래스이다.

2) Builder를 사용하는 경우

 
  Widget build(BuildContext context) {
    return new Scaffold(
        appBar: new AppBar(
          title: new Text(widget.title),
        ),
        body: new Container(),
        /// Scaffold doesn't exist in this context here
        /// because the context thats passed into 'build'
        /// refers to the Widget 'above' this one in the tree,
        /// and the Scaffold doesn't exist above this exact build method
        ///
        /// This will throw an error:
        /// 'Scaffold.of() called with a context that does not contain a Scaffold.'
        floatingActionButton: new FloatingActionButton(onPressed: () {
          Scaffold.of(context).showSnackBar(
                new SnackBar(
                  content: new Text('SnackBar'),
                ),
              );
        }));
  }

body와 FAB사이에 주석의 내용은 다음과 같다.
build함수에 전달받은 context내에 scaffold가 존재하지 않기 때문에 아래 FAB 버튼을 눌렀을 경우 다음과 같은 에러 문구를 반환할것이다.
'Scaffold를 포함하지 않은 context를 가지고 Scaffold.of()함수를 호출하였다.'

이러한 경우를 방지하기 위해 사용하는 것이 builder 클래스이다.

3) Builder 사용방법


  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text(widget.title),
      ),
      body: new Container(),
      /// Builders let you pass context
      /// from your *current* build method
      /// Directly to children returned in this build method
      ///
      /// The 'builder' property accepts a callback
      /// which can be treated exactly as a 'build' method on any
      /// widget
      floatingActionButton: new Builder(builder: (BuildContext context) {
        return new FloatingActionButton(onPressed: () {
          Scaffold.of(context).showSnackBar(
                new SnackBar(
                  backgroundColor: Colors.blue,
                  content: new Text('SnackBar'),
                ),
              );
        });
      }),
    );
  }

위와 같이 위젯을 선언하는 경우, builder내의 buildContext는 현재 실행되고 있는 build 함수의 buildContext를 통해 위젯이 생성된다. 그렇기 때문에 Scaffold.of()를 실행하여도 해당 context내에 scaffold가 있기 때문에 에러가 나지 않는다.

profile
어제보다 한 발짝 더 나아가려는 Flutter 개발자

0개의 댓글