Flutter - #14. Radio

Pearl Lee·2021년 6월 8일
1

Flutter Widget

목록 보기
14/50

내가 보려고 쓰는 Flutter 일기
출처 : https://api.flutter.dev/flutter/material/Radio-class.html




Radio

라디오 버튼은 플러터에만 있는게 아니라 프론트엔드에서 자주 쓰는 유명한 버튼이다. 하나만 선택이 가능한 목록에 쓰기 좋다. 중복 선택이 안 되기 때문이다. Enumerator(열거형)와 자주 같이 쓰인다. 왜 그럴까?


라디오 버튼을 쓰려면 value, groupValue, onChanged 속성을 설정해야 한다.

Radio 버튼을 공식 문서에서 찾아보면, Radio class라고 되어있다. T 에 라디오 버튼이 다루게 될 타입이 들어가는데, 여기서 Enumerator를 쓰는 것이다. T에는 Enumerator로 선언한 변수를 넣어주고, value에는 Enumerator 중의 특정 값을 넣는 것이다. value는 해당 라디오 버튼에 나타나는 값을 의미한다.

groupValue는 라디오 버튼 그룹 중에서 현재 선택된 값을 나타낸다.

onChanged 속성에서 groupValue를 변경해준다. value를 인자로 넘기는 콜백 함수를 작성해서, groupValue값을 value값으로 변경하는 것이다. groupValue=value가 되면 해당 버튼이 선택된다.
setState(){}; 안에 넣어줘야 하는 것을 잊지 말자.









코드 예시로 알아보자

공식 문서에서 제공하는 코드를 가져와서, 열거형 변수만 변경하여 돌려보았다. (처음에는 공식 문서의 열거형인 Singingcharacter 선언부를 못 찾아서, 플러터에서 제공하는 특이한 변수인 줄 알았다. 그래서 난 쉬운 과일이름으로^^)



import 'package:flutter/material.dart';

void main() => runApp(const MyApp());

/// This is the main application widget.
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);

static const String _title = 'Test Radio Button';


Widget build(BuildContext context) {
  return MaterialApp(
    title: _title,
    home: Scaffold(
      appBar: AppBar(title: const Text(_title)),
      body: const Center(
        child: RadioButtonWidget(),
      ),
    ),
  );
}
}

enum Fruit { Apple, Grapes, Pear, Lemon }

/// This is the stateful widget that the main application instantiates.
class RadioButtonWidget extends StatefulWidget {
const RadioButtonWidget({Key? key}) : super(key: key);


State<RadioButtonWidget> createState() => _RadioButtonWidgetState();
}

/// This is the private State class that goes with MyStatefulWidget.
class _RadioButtonWidgetState extends State<RadioButtonWidget> {
//처음에는 사과가 선택되어 있도록 Apple로 초기화 -> groupValue에 들어갈 값!
Fruit? _fruit = Fruit.Apple;


Widget build(BuildContext context) {
  return Column(
    children: <Widget>[
      ListTile(
        //ListTile - title에는 내용, 
	//leading or trailing에 체크박스나 더보기와 같은 아이콘을 넣는다.
        title: const Text('Apple'),
        leading: Radio<Fruit>(
          value: Fruit.Apple,
          groupValue: _fruit,
          onChanged: (Fruit? value) {
            setState(() {
              _fruit = value;
            });
          },
        ),
      ),
      ListTile(
        title: const Text('Grapes'),
        leading: Radio<Fruit>(
          value: Fruit.Grapes,
          groupValue: _fruit,
          onChanged: (Fruit? value) {
            setState(() {
              _fruit = value;
            });
          },
        ),
      ),
      ListTile(
        title: const Text('Pear'),
        leading: Radio<Fruit>(
          value: Fruit.Pear,
          groupValue: _fruit,
          onChanged: (Fruit? value) {
            setState(() {
              _fruit = value;
            });
          },
        ),
      ),
      ListTile(
        title: const Text('Lemon'),
        leading: Radio<Fruit>(
          value: Fruit.Lemon,
          groupValue: _fruit,
          onChanged: (Fruit? value) {
            setState(() {
              _fruit = value;
            });
          },
        ),
      ),
    ],
  );
}
}

사과 선택포도 선택






ListTile은 저번에 포스팅을 해서 다시 보고 이해하였다. 역시 날 위한 내 블로그...

오늘의 일기는 여기까지!

profile
안 되면 되게 하라

0개의 댓글