Flutter Tutorials

Flutter app development tutorials


flutter – Radio button onChanged

main.dart


import 'package:flutter/material.dart';

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

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        title: 'Flutter Example',
        theme: ThemeData(primarySwatch: Colors.indigo),
        home: const StateExample()
    );
  }
}

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

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


class _StateExampleState extends State<StateExample> {
  Map<String,Color> values = {
    "Red" : Colors.red,
    "Green" : Colors.green,
    "Yellow" : Colors.yellow,
    "Pink" : Colors.pink,
    "Orange" : Colors.orange,
    "Teal" : Colors.teal,
    "Indigo" : Colors.indigo
  };

  Color _selected = Colors.orange;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: const Color(0xFFF5F5F5),
        appBar: AppBar(
            title: const Text("Flutter - Radio Button onChanged")
        ),
        body: bodyContent()
    );
  }


  bodyContent() {
    return ListView(
      children: values.keys.map((String key){
        return RadioListTile<Color>(
            tileColor: _selected == values[key]
                ? values[key] : Colors.grey[200],
            title: Text(key),
            value: values[key]??_selected,
            groupValue: _selected,
            onChanged: (Color? value){
              setState(() {
                _selected = value??_selected;
              });
            }
        );
      }).toList(),
    );
  }
}

More flutter tutorials



About Me

Flutter Developer

Design a site like this with WordPress.com
Get started