Flutter

CheckBox Inner Color Not Changed

kahnco 2022. 12. 28. 16:33

Flutter에서 CheckBox를 구현하다보면, 선택되지 않은 상태에서의 내부 색상을 변경하고 싶을 때가 있습니다.

 

이런 경우에 다른 Widget들 처럼, MaterialState 상태를 분기시켜서 selected 되지 않은 상태일 때에 원하는 값을 넣으면 될 것처럼 보입니다.

 

코드로 구현해보면,

 

Checkbox(
    fillColor: MaterialStateProperty.resolveWith(setCheckBoxColorState),
    value: isChecked,
    onChanged: (value) {},
);

...

Color? setCheckBoxColorState(Set<MaterialState> states) {
    if (states.contains(MaterialState.selected)) {
        return Colors.black;
    }
    return Colors.pink;
}

대략적으로 이런 느낌입니다.

 

하지만 위 코드를 그대로 돌려보면 unSelected 상태에서 분홍색으로 채워지지 않는 모습을 발견할 수 있습니다.

 

이에 대한 이유는 Flutter 공식 문서에서 CheckBox에 관련된 내용을 보면 알 수 있습니다.

 

A Material Design checkbox.

The checkbox itself does not maintain any state. Instead, when the state of the checkbox changes, the widget calls the onChanged callback. Most widgets that use a checkbox will listen for the onChanged callback and rebuild the checkbox with a new value to update the visual appearance of the checkbox.

The checkbox can optionally display three values - true, false, and null - if tristate is true. When value is null a dash is displayed. By default tristate is false and the checkbox's value must be true or false.

Requires one of its ancestors to be a Material widget.

중요하게 보아야할 내용은 두번째 줄입니다.

The checkbox itself does not maintain any state

 

Checkbox는 그 자체로 state를 가지지 않기 때문에 MaterialState로 분기시키는 방법은 올바르지 않습니다.

 

따라서 공식적으로는 Checkbox의 내부를 칠할 수 있는 방법은 없습니다.

 

이에 저는 Checkbox의 뒤에 색상을 가지는 Container를 집어넣어서 이를 해결했습니다.

 

Container(
    height: 24.sp,
    width: 24.sp,
    decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(48),
    ),
    child: Transform.scale(
        scale: 1.6,
        child: Checkbox(
            value: isChecked,
            onChanged: (value) {},
            shape: CircleBorder(),
        ),
    ),
);
반응형

'Flutter' 카테고리의 다른 글

In Flutter, which Empty Widget is most fastest?  (0) 2023.01.29
Flutter with ChannelTalk  (0) 2023.01.06
Flutter Build Flavor with Firebase (1)  (0) 2023.01.04
Flutter Clean Architecture  (0) 2022.12.28