Flutter

Flutter 아이폰 스위치 CupertinoSwitch 만들기 (StatelessWidget)

해니01_15 2024. 1. 17. 16:49

 

오늘은 위와 같은 아이폰 토글 스위치를 구현 해보고자 한다. 

 

 

[ CupertinoSwitch ]

CupertinoSwitch 라는 CupertinoSwitch는 iOS 앱에서 사용되는 스위치를 나타내는 Cupertino 디자인을 따르는 위젯이다. 이 위젯은 Flutter 프레임워크에서 제공되며, iOS 스타일의 스위치를 생성하는 데 사용된다. 

 

 

flutter 에서 제공하는 것인 만큼 내가 저번에 만들었던 토글 버튼과는 비교도 안되게 아주 가성비 넘치는 편리성을 자랑한다.. 

혹시 전에 힘들게 구현했던 togglebutton이 궁금하다면 아래로 ... ㅎ

 

Flutter toggleButtons 만들기

이렇게 달러를 클릭하면 달러의 주식가격이 원을 클릭하면 원화 가격이 나오게 토글버튼을 구현 해보려고 한다. 먼저 토글 버튼과 금액을 다른 컨테이너로 움직이기 때문에 (눈속임... 이라고

henniee.tistory.com

 

 

[ CupertinoSwitch 옵션 값 ]

  • value (required) : 데이터 바인딩에 사용되는 불리언 값으로, 스위치의 현재 상태를 나타낸다.
  • onChanged (required) : 스위치의 상태가 변경될 때 호출되는 콜백 함수로, 이 콜백은 새로운 값과 함께 호출 된다.
  • activeColor : 활성 상태일 때의 스위치 배경 색상을 정의한다. 이 값이 제공되지 않으면 기본 iOS 색상이 사용됨
  • trackColor : 스위치의 바탕 색상을 정의한다. 이 값이 제공되지 않으면 기본 iOS 색상이 사용된다.
  • thumbColor : 스위치의 썸네일(동그란 드래그하는 부분) 색상을 정의한다. 기본 iOS 색상이 적용.
  • dragStartBehavior : 사용자가 스위치를 드래그할 때의 동작을 정의한다. 기본은 start로 되어 있고 스위치를 드래그 할 때 이동이 시작 된다. 

 

 

[ StatefulWidget ]

StatefulWidget 을 이용하여 구현 하는 방법은 아래 문서를 참조하면 된다. 

 

CupertinoSwitch class - cupertino library - Dart API

An iOS-style switch. Used to toggle the on/off state of a single setting. The switch itself does not maintain any state. Instead, when the state of the switch changes, the widget calls the onChanged callback. Most widgets that use a switch will listen for

api.flutter.dev

 

 

[ StatelessWidget ]

 

controller에 toggleAlram 이라는 obs 변수를 설정해 두었다. 이 값을 value 값으로 지정하고 , 상태가 변할 때 마다 (onChanged)  value와 반대의 값으로 바꿔준다. 그리고 값이 바뀔 때 SharedPreference에 해당 값을 저장해서 앱을 종료하고 켰을 때도 알람을 어떤 상태로 유지 할 것인지 저장 해준다.  또한 이 CupertinoSwitch를 Obx로 감싸서 화면이 전환 될 때 그 변한 값이 유지 되도록 해준다. 

  Row(children: [
              Icon(Icons.alarm_off_outlined, size: textSizeTitle),

              SizedBox(width: 5),
              CupertinoSwitch(
                value: _controller.toggleAlarm.value,
                thumbColor: Colors.green,
                activeColor: Colors.grey,
                onChanged: (bool? value) {
                  _controller.toggleAlarm.value =
                      !_controller.toggleAlarm.value;

                  StoreUtils.instance.setAlarm(_controller.toggleAlarm.value);
                },
              ),
              SizedBox(width: 5),
              Icon(Icons.alarm, size: textSizeTitle),
            ])
//Build 에서 사용 될 Obx 
Obx(() {
  return toggleAlarmButton(widthDis);
     }),
  
  
  
  ========= Controller Page =============
  
  //값을 우선 true 로 설정 
  RxBool toggleAlarm = true.obs;
  
 //페이지를 build 할 때 초기화 
  void init() {
  
 // 만약에 체크 알람이 false (알람 안 울리도록 설정 되어 있으면)
 var checkAlarm = StoreUtils.instance.getAlarm();
    if (checkAlarm == false) {
      toggleAlarm.value = false;
    }
}