Flutter/개발

[ Flutter ] RadioButton 사용법

Always Newbie 2022. 3. 11. 21:35
반응형
SMALL

👼🏻 초보 안드로이드 개발자가 매번 구글링하기 싫어서 정리하는 블로그 👼🏻 

 

안녕하세요! 🙋🏻‍♀️

Flutter 의 RadioButton 사용법을 간단쓰하게 해보겠습니다!

Radio Button 클릭 시 Toast!

📍 RadioListTile Widget
RadioListTile(
  value: value,
  groupValue: groupValue,
  onChanged: onChanged,
)

사용한 위젯은 " RadioListTile " 라는 위젯을 사용했습니다!

반응형

전체 코드 공유 드립니다!

import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';

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

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: "Radio Button",
      debugShowCheckedModeBanner: false,
      home: RadioButtons(),
    );
  }
}

class RadioButtons extends StatefulWidget {
  const RadioButtons({Key? key}) : super(key: key);

  @override
  _RadioButtonsState createState() => _RadioButtonsState();
}

enum Char { A, B, C, D }

class _RadioButtonsState extends State<RadioButtons> {
  Char _char = Char.A; // 라디오 버튼의 선택 초기화

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Radio Button"),
        centerTitle: true,
      ),
      body: Center(
        child: Column(
          children: [
            RadioListTile(
              title: Text("A"),
              value: Char.A,
              groupValue: _char,
              onChanged: (Char? value) {
                setState(() {
                  _char = value!;
                  showToast("A");
                });
              },
            ),
            RadioListTile(
              title: Text("B"),
              value: Char.B,
              groupValue: _char,
              onChanged: (Char? value) {
                setState(() {
                  _char = value!;
                  showToast("B");
                });
              },
            ),
            RadioListTile(
              title: Text("C"),
              value: Char.C,
              groupValue: _char,
              onChanged: (Char? value) {
                setState(() {
                  _char = value!;
                  print(_char.name); // _char 에 담긴 값은 이렇게
                  showToast("C");
                });
              },
            ),
            RadioListTile(
              title: Text("D"),
              value: Char.D,
              groupValue: _char,
              onChanged: (Char? value) {
                setState(() {
                  _char = value!;
                  print(value);
                  showToast("D");
                });
              },
            ),
          ],
        ),
      ),
    );
  }

  void showToast(String value) {
    Fluttertoast.showToast(
        msg: "$value 선택",
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.BOTTOM);
  }
}

 

틀린부분이 있거나, 궁금하신게 있거나, 그냥 아무말이나 하고싶으면 댓글 남겨주세요 🥴

봐주셔서 감사합니다 🥰

반응형
LIST