Button으로 Drawer열기

Clean Code Big Poo·2023년 4월 18일
0

Flutter

목록 보기
28/38
post-thumbnail

Overview

AppBar를 커스텀으로 정의하였다. Appbar처럼 보이는 Container이다. 여기의 메뉴 버튼으로 Drawer을 열어보자.

Drawer가 안 열려

아래와 같은 예제로 테스트를 해보면 drawer가 열리지 않는다. Scaffold.of(context).hasDrawer에서도 false가 떨어진다..

import 'package:flutter/material.dart';

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

  
  Widget build(BuildContext context) {
    return Scaffold(
      drawer: Drawer(),//이곳에 Drawer을 넣어주어야 함.
      body: SafeArea(
        child: Center(
          child: TextButton(onPressed: (){
            Scaffold.of(context).openDrawer();
          }, child: Text('Open Drawer')),
        ),
      ),
    );
  }
}

Drawer을 열어보자.

stack over flow 고수님들에게 자문을 구해보자. 크게 두가지 방법이 있었다.

GlobalKey

GlobalKey를 사용하여 scaffold key를 매칭한다. drawer가 열리길 원하는 이벤트에 _scaffoldKey.currentState.openDrawer()를 추가한다.

import 'package:flutter/material.dart';

class HomePage extends StatelessWidget {
  const HomePage({Key? key}) : super(key: key);
  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();

  
  Widget build(BuildContext context) {
    return Scaffold(
      key: _scaffoldKey,
      drawer: Drawer(),//이곳에 Drawer을 넣어주어야 함.
      body: SafeArea(
        child: Center(
          child: TextButton(onPressed: (){
            Scaffold.of(context).openDrawer();
          }, child: Text('Open Drawer')),
        ),
      ),
    );
  }
}

Builder

drawer가 열리길 원하는 위젯을 Builder로 감싸버린다.

해당 코드에서 Scaffold.of(context)에서 context는 build메소드의 BuildContext이다. 우리가 찾고싶은 Scaffold는 build 메소드 아래에(widget tree관점에서) 있기 때문에 찾지 못하는것. by th_bigLight

		Builder(
              builder: (context) {
                return IconButton(
                  icon: Icon(
                    Icons.menu,
                    color: Colors.white,
                    size: 30.sp,
                  ),
                  onPressed: () {
                    Scaffold.of(context).openDrawer();
                  }, //TODO:메뉴 - drawer
                );
              }
            ),

참고

https://th-biglight.tistory.com/26

https://www.youtube.com/watch?v=ts9n211n8ZU&t=488s

https://www.google.com/search?q=Scaffold.of(context).openDrawer()%3B&oq=Scaffold.of(context).openDrawer()%3B&aqs=chrome..69i57j0i19i512j0i19i30j0i5i19i30.551j0j4&sourceid=chrome&ie=UTF-8

0개의 댓글