본문 바로가기
프로그래밍/Flutter

[ Flutter Widget ] 플러터 기본위젯 - Radio

by 호랑이탈 2025. 1. 1.
반응형

Flutter 기본위젯 - Radio 위젯

사용자에게 옵션 중 하나를 선택하도록 하는 단일 선택 도구입니다. 각 Radio 위젯은 동일한 groupValue를 공유하며, 사용자가 선택한 값을 관리할 수 있습니다.

 

Radio 함수 원형

const Radio({
  super.key,
  required this.value,
  required this.groupValue,
  required this.onChanged,
  this.mouseCursor,
  this.toggleable = false,
  this.activeColor,
  this.fillColor,
  this.focusColor,
  this.hoverColor,
  this.overlayColor,
  this.splashRadius,
  this.materialTapTargetSize,
  this.visualDensity,
  this.focusNode,
  this.autofocus = false,
})

 

 

매개변수 상세 설명


1. value (필수)
설명: Radio 위젯이 선택되었을 때 반환할 값입니다.
타입: T (제네릭 타입)

value: 'Option 1',

 


2. groupValue (필수)
설명: 현재 선택된 Radio의 값을 나타냅니다. value와 일치하면 해당 Radio가 선택된 상태가 됩니다.
타입: T?

groupValue: selectedOption,

 


3. onChanged (필수)
설명: Radio가 선택될 때 호출되는 콜백 함수입니다.
타입: ValueChanged<T?>?

onChanged: (value) {
  print('Selected: $value');
},

 

 

4. mouseCursor
설명: 라디오 버튼 위에 마우스를 올렸을 때 나타나는 커서를 설정합니다.
타입: MouseCursor?

mouseCursor: SystemMouseCursors.click,

 


5. toggleable
설명: true로 설정하면 이미 선택된 Radio를 다시 눌러 선택을 해제할 수 있습니다.
타입: bool
기본값: false

toggleable: true,

 


6. activeColor
설명: 선택된 상태에서 Radio의 색상을 설정합니다.
타입: Color?

activeColor: Colors.green,

 


7. fillColor
설명: 라디오 버튼 내부 색상을 상태별로 설정합니다.
타입: MaterialStateProperty<Color?>?

fillColor: MaterialStateProperty.resolveWith((states) {
  if (states.contains(MaterialState.selected)) {
    return Colors.blue;
  }
  return Colors.grey;
}),

 


8. focusColor
설명: 라디오 버튼이 포커스를 받을 때 나타나는 색상입니다.
타입: Color?

focusColor: Colors.orange,

 


9. hoverColor
설명: 마우스가 라디오 버튼 위에 있을 때 나타나는 색상입니다.
타입: Color?

hoverColor: Colors.yellow,

 


10. overlayColor
설명: 클릭 또는 터치 시 나타나는 오버레이 색상입니다.
타입: MaterialStateProperty<Color?>?

overlayColor: MaterialStateProperty.resolveWith((states) {
  if (states.contains(MaterialState.pressed)) {
    return Colors.purple.withOpacity(0.5);
  }
  return null;
}),

 


11. splashRadius
설명: 클릭 시 스플래시 효과의 반지름을 설정합니다.
타입: double?

splashRadius: 24.0,

 


12. materialTapTargetSize
설명: 터치 가능한 영역의 크기를 설정합니다.
타입: MaterialTapTargetSize?

materialTapTargetSize: MaterialTapTargetSize.padded,

 


13. visualDensity
설명: 라디오 버튼의 밀도를 설정합니다.
타입: VisualDensity?

visualDensity: VisualDensity.compact,

 


14. focusNode
설명: 라디오 버튼의 포커스를 제어하는 노드입니다.
타입: FocusNode?

focusNode: FocusNode(),

 


15. autofocus
설명: 라디오 버튼이 처음 렌더링될 때 자동으로 포커스를 받을지 여부를 설정합니다.
타입: bool
기본값: false

autofocus: true,

 

 

샘플코드

import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Radio Full Example'),
        ),
        body: const Padding(
          padding: EdgeInsets.all(16.0),
          child: RadioExample(),
        ),
      ),
    );
  }
}

class RadioExample extends StatefulWidget {
  const RadioExample({super.key});

  @override
  State<RadioExample> createState() => _RadioExampleState();
}

class _RadioExampleState extends State<RadioExample> {
  String? _selectedOption = 'Option 1'; // 현재 선택된 값

  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Radio<String>(
          value: 'Option 1', // 첫 번째 옵션 값
          groupValue: _selectedOption, // 현재 선택된 그룹 값
          onChanged: (value) {
            // 상태 변경 시 호출
            setState(() {
              _selectedOption = value;
            });
          },
          toggleable: true, // 선택 해제 가능
          activeColor: Colors.green, // 선택된 상태 색상
          fillColor: MaterialStateProperty.resolveWith((states) {
            if (states.contains(MaterialState.selected)) {
              return Colors.blue;
            }
            return Colors.grey;
          }),
          focusColor: Colors.red, // 포커스 상태 색상
          hoverColor: Colors.orange, // 호버 상태 색상
          overlayColor: MaterialStateProperty.resolveWith((states) {
            if (states.contains(MaterialState.pressed)) {
              return Colors.purple.withOpacity(0.5); // 클릭 시 색상
            }
            return null;
          }),
          splashRadius: 24.0, // 스플래시 반경
          materialTapTargetSize: MaterialTapTargetSize.padded, // 터치 영역 크기
          visualDensity: VisualDensity.adaptivePlatformDensity, // 밀도 설정
          autofocus: true, // 자동 포커스
        ),
        Radio<String>(
          value: 'Option 2', // 두 번째 옵션 값
          groupValue: _selectedOption, // 현재 선택된 그룹 값
          onChanged: (value) {
            // 상태 변경 시 호출
            setState(() {
              _selectedOption = value;
            });
          },
        ),
        SizedBox(height: 20),
        Text('Selected Option: $_selectedOption'), // 현재 선택된 옵션 출력
      ],
    );
  }
}

 

주요 기능 설명

 

  1. 그룹 선택 및 선택 해제:
    • toggleable를 통해 선택 해제 가능.
  2. 스타일링:
    • fillColor, activeColor, hoverColor, focusColor, overlayColor를 활용해 다양한 스타일 적용.
  3. 포커스 및 상호작용:
    • focusNode와 autofocus를 사용해 포커스 관리.
  4. 스플래시 효과:
    • splashRadius와 overlayColor로 클릭 효과 조정.

 

 

 

 

 

 

반응형