티스토리 뷰

이전 글에서는 TextButton, ElevatedButton, OutlinedButton 즉 하나의 버튼 만을 알아봤습니다.

그런데 하나의 버튼이 아닌 여러 개의 버튼이 필요할 때가 있겠죠?

가장 많이 쓰이는것은 ToggleButtons, DropdownButton, PopupMenuButton입니다
각 버튼들이 어떻게 다른지 그리고 어떤 상황에서 쓰이는지 한번 알아볼게요

역시나 글로 설명하는것 보다는 직접 실험을 할 수 있도록 dartpad를 준비했습니다.

 

 

ToggleButtons class

ToggleButtons는 child 버튼들이 row로 표시됩니다. 각 버튼의 state는 isSelected로 결정이 됩니다.

그래서 버튼들의 개수에 맞게 bool 리스트를 넘겨줘야합니다.

ToggleButtons(
    children: <Widget>[
      Icon(Icons.ac_unit),
      Icon(Icons.call),
      Text("WIFI"),
    ],
    onPressed: (int index) {
      setState(() {
        _selections1[index] = !_selections1[index];
      });
    },
    isSelected: _selections1,
  ),

기본적으로 제공되는 ToggleButtons은 row로 밖에 못 쓰지만 RotatedBox를 쓰면 약간의 꼼수(?)로 column처럼 보이게 할 수 있습니다.

RotatedBox(
quarterTurns: 1,
  child: ToggleButtons(
    color: Colors.greenAccent,
    children: <Widget>[
             RotatedBox(quarterTurns: 3, child: Icon(Icons.format_bold)),
             RotatedBox(quarterTurns: 3, child: Icon(Icons.format_italic)),
             RotatedBox(quarterTurns: 3, child: Icon(Icons.link)),
        ],
    isSelected: isSelected,
  ),
)

DropdownButton class

DropdownButton은 list의 버튼들 중에서 선택할 때 쓰입니다. DropdownButton은 현재 선택된 item을 보여주면, 버튼을 누를 때 선택할 수 있는 item들을 보여줍니다.

타입 T는 각 dropdown item의 value를 의미합니다. Dropdown의 list의 버튼은 무조건 해당 T의 value 이 여아 합니다. 일반적으로 enum이 이용됩니다.

enum MenuType { first, second, third }

onChanged 콜백은 선택한 dropdown value를 업데이트합니다. 일반적으로 setState를 호출해서 새롭게 선택된 value로 업데이트합니다.

DropdownButton(
    value: _dropdownValue,
    items: MenuType.values
        .map((value) => DropdownMenuItem(
              value: value,
              child: Text(value.toShortString()),
            ))
        .toList(),
    onChanged: (newValue) {
      setState(() {
        _dropdownValue = newValue;
      });
    },
    elevation: 4,
  )

PopupMenuButton class

앞서 설명한 DropdownButton와 비슷한데, item을 선택했을대 menu는 dismiss가 됩니다. 즉 현재 선택한 item이 표시되지 않는 점이 Dropdown Button과 PopupMenuButton의 차이점이 되겠네요.

PopupMenuButton에 icon이 제공되는 경우 IconButton처럼 행동하게 됩니다.

PopupMenuButton<MenuType>(
  icon: Icon(Icons.settings),
  onSelected: (MenuType result) {
    setState(() {
      _selection = result;
    });
  },
  itemBuilder: (BuildContext context) => MenuType.values
      .map((value) => PopupMenuItem(
            value: value,
            child: Text(value.toShortString()),
          ))
      .toList(),
), 

'Flutter' 카테고리의 다른 글

플러터 3.10  (0) 2023.05.13
Flutter와 Material 3  (0) 2023.04.08
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함