상세 컨텐츠

본문 제목

[플러터] AppBar - actions, Scaffold - EndDrawer 함께 사용하기

플러터/오류, 삽질 및 해결방법

by 감자 바보 2025. 1. 1. 14:47

본문

반응형

[플러터] AppBar - actions, Scaffold - EndDrawer 함께 사용하기

 

발생 오류

 

AppBar의 actions 아이콘과 EndDrawer를 함께 사용할 시 EndDrawer가 정상적으로 동작하지 않는다.

 

Scaffold(
      appBar: AppBar(
        title: Row(
            children: [
            ],
          ),
        actions: [
          Visibility(
              visible: !_searchFlag,
              child:
                  IconButton(onPressed: () {
                    Scaffold.of(context).openEndDrawer();
                  }, icon: const Icon(Icons.menu))),
      ),
      endDrawer: Drawer(
        child: ListView(
          children: [
            
          ],
        ),
      ),

 

해결 방법

 

GlobalKey를 활용하여 이를 해결했습니다.

 

1. 먼저 GlobalKey 변수를 선언하고 Scaffold에 등록해 줍니다.

 

    final _scaffoldKey = GlobalKey<ScaffoldState>();
    
    Scaffold(
    	key: _scaffoldKey,
    )

 

 

2. AppBar의 actions의 아이콘 버튼에 등록한 키를 이용하여 EndDrawer를 열어줍니다.

 

Scaffold(
  key: _scaffoldKey,
  appBar: AppBar(
    title: Row(
        children: [
        ],
      ),
    actions: [
      child:
          IconButton(onPressed: () {
            _scaffoldKey.currentState?.openEndDrawer();
      	}, icon: const Icon(Icons.menu)),
  ),
  endDrawer: Drawer(
    child: ListView(
      children: [
            
      ],
    ),
  ),

 

코드 원문

  Widget build(BuildContext context) {
    final _scaffoldKey = GlobalKey<ScaffoldState>();
    return Scaffold(
      key: _scaffoldKey,
      appBar: AppBar(
        title: Row(
            children: [
            ],
          ),
        actions: [
          Visibility(
              visible: !_searchFlag,
              child:
                  IconButton(onPressed: () {
                    _scaffoldKey.currentState?.openEndDrawer();
                  }, icon: const Icon(Icons.menu))),
      ),
      endDrawer: Drawer(
        child: ListView(
          children: [
            
          ],
        ),
      ),
  }

 

 

마무리

 

GlobalKey를 이용하여 AppBar의 actions와 Scaffold의 EndDrawer를 함께 사용할 수 있습니다.

 

참고

 

1. Flutter Scaffold, Actions and End Drawer together? - Stack Overflow

 

Flutter Scaffold, Actions and End Drawer together?

In Scaffold if 'actions' parameter is used it hides the 'endDrawer'. Is it possible to display both? var tmp = new Scaffold( /// end drawer endDrawer: Container(color: Colors.red, ch...

stackoverflow.com

 

728x90
반응형