How To Show Selected Radio Button In Radio Group In Flutter

admin_img Posted By Bajarangi soft , Posted On 27-11-2020

The radio button itself does not maintain any state. Instead, selecting the radio invokes the onChanged callback, passing value as a parameter. If groupValue and value match, this radio will be selected. Most widgets will respond to onChanged by calling State.setState to update the radio button's groupValue.

How To Show Selected Radio Button In Radio Group In Flutter

Show Selected Radio Button In Radio Group
Complete Code For Show Selected Radio Button In Radio Group In Flutter 
main.dart

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: ShowSelectRadio(),
    );
  }
}
class ShowSelectRadio extends StatefulWidget {
  @override
  ShowSelectRadioState createState() {
    return new ShowSelectRadioState();
  }
}

class ShowSelectRadioState extends State<ShowSelectRadio> {
  int _currentVal = 1;
  String _currentText = 'Flutter';

  List<GroupModel> _group = [
    GroupModel(
      text: "Flutter",
      index: 1,
    ),
    GroupModel(
      text: "Ios",
      index: 2,
    ),
    GroupModel(
      text: "Dart",
      index: 3,
    ),
    GroupModel(
      text: "Android",
      index: 4,
    ),
    GroupModel(
      text: "Laravel",
      index: 5,
    ),
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.lightGreen,
        title: Text("Show Selected Radio"),
      ),
      body: Column(
        children: <Widget>[
          Expanded(
            child: Center(
              child: Text(_currentText,
                  style: TextStyle(
                    fontSize: 20.0,
                    fontWeight: FontWeight.bold,
                  )),
            ),
          ),
          Expanded(
              child: Container(
                height: 350.0,
                child: Column(
                  children: _group
                      .map((t) => RadioListTile(
                    title: Text("${t.text}",),
                    groupValue: _currentVal,
                    value: t.index,
                    onChanged: (val) {
                      setState(() {
                        _currentVal = val.index;
                        _currentText = t.text;
                      });
                    },
                  ))
                      .toList(),
                ),
              )),
        ],
      ),
    );
  }
}

class GroupModel {
  String text;
  int index;
  GroupModel({this.text, this.index});
}

Related Post