Custom Widget Radio Button In Flutter

Custom Widget Radio Button In Flutter :

Screenshot:

Custom Widget Radio Button In Flutter

base_select.dart

import 'package:flutter/material.dart';

class BaseSelect extends StatefulWidget {
  final bool selected;
  final ValueChanged<bool> onChange;
  final Function(BuildContext, Animation) builder;

  const BaseSelect(
      {Key key, this.selected = false, this.onChange, @required this.builder})
      : super(key: key);

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

class _MyRadioButtonState extends State<BaseSelect>
    with SingleTickerProviderStateMixin {
  bool _checked;
  AnimationController _controller;

  initState() {
    super.initState();
    _checked = widget.selected;
    _controller = AnimationController(
      duration: Duration(milliseconds: 200),
      value: _checked ? 1.0 : 0.0,
      vsync: this,
    );
  }

  @override
  void didUpdateWidget(BaseSelect oldWidget) {
    super.didUpdateWidget(oldWidget);
    _checked = widget.selected;
    if (_checked) {
      _controller.forward();
    } else {
      _controller.reverse();
    }
  }

  @override
  dispose() {
    _controller.dispose();
    super.dispose();
  }

  _toggle() {
    setState(() {
      _checked = !_checked;
      if (widget.onChange != null && widget.onChange is Function(bool)) {
        widget.onChange(_checked);
      }
      if (_checked) {
        _controller.forward();
      } else {
        _controller.reverse();
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: _toggle,
      child: widget.builder(context, _controller),
    );
  }
}

custom_radio_button.dart

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

class CustomRadioButton extends StatelessWidget {
  final double size;
  final bool selected;
  final Color color;
  final ValueChanged<bool> onChange;

  const CustomRadioButton({
    Key key,
    this.size = 10.0,
    this.selected = false,
    this.color = Colors.grey,
    this.onChange,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return BaseSelect(
      selected: selected,
      onChange: onChange,
      builder: (BuildContext context, Animation animation) {
        return Container(
          width: size,
          height: size,
          child: CustomPaint(
            painter: CustomRadioButtonPainter(
                animation: animation, checked: true, color: color),
          ),
        );
      },
    );
  }
}

class CustomRadioButtonPainter extends CustomPainter {
  final Animation animation;
  final Color color;
  final bool checked;

  CustomRadioButtonPainter({this.animation, this.checked, this.color})
      : super(repaint: animation);

  @override
  void paint(Canvas canvas, Size size) {
    final Offset center = Offset(size.width / 1, size.height / 1);
    final Paint borderPaint = Paint()
      ..color = color
      ..strokeWidth = 1.0
      ..style = PaintingStyle.stroke;

    final Paint innerCirclePaint = Paint()
      ..color = color.withOpacity(animation.value);

    canvas.drawCircle(center, size.width / 1, borderPaint);

    canvas.drawCircle(center, size.width / 1 - 3.0, innerCirclePaint);

  }

  @override
  bool shouldRepaint(CustomRadioButtonPainter oldDelegate) {
    return oldDelegate.checked != checked;
  }
}

main.dart

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

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

class HelloWorldApp extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return new AddTodoFormState();
  }
}

class AddTodoFormState extends State<HelloWorldApp> {
  Map<String, dynamic> _formData = {
    'text': null,
    'category': null,
    'date': null,
    'time': null,
  };

  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      home: new Scaffold(
          body: Container(
              margin: EdgeInsets.only(top: 20),
              child: Column(
                children: Categories.initial().categories.map((Category cat) {
                  final bool selected = _formData['category']?.name == cat.name;
                  return ListTile(
                      contentPadding: EdgeInsets.only(left: 10.0, right: 10.0),
                      title: Align(
                        child: new Text( '${cat.name}', style: Theme.of(context).textTheme.body2),
                        alignment: Alignment(-1.2, 0),
                      ),

                      leading: CustomRadioButton(
                          color: cat.color,
                          selected: selected,
                          onChange: (newVal) {
                            _handleCategoryChange(newVal, cat);
                          }),
                      onTap: () {
                        if (selected) {
                          _handleCategoryChange(false, cat);
                        } else {
                          _handleCategoryChange(true, cat);
                        }
                      });
                }).toList(),
              ))),
    );
  }

  void _handleCategoryChange(bool newVal, Category category) {
    setState(() {
      if (newVal) {
        _formData['category'] = category;
      } else {
        _formData['category'] = null;
      }
    });
  }
}

class Category {
  final String name;
  final Color color;
  int todosNumber;
  final IconData icon;

  Category({this.name, this.todosNumber = 0, this.color, this.icon});
}

class Categories {
  final List<Category> categories;

  Categories(this.categories);

  factory Categories.initial() {
    return Categories(
      <Category>[
        Category(name: 'College', color: Colors.red, icon: Icons.school),
        Category(name: 'Work', color: Colors.blue, icon: Icons.work),
        Category(
            name: 'Study',
            color: Colors.yellow,
            icon: Icons.chrome_reader_mode),
        Category(name: 'Sport', color: Colors.green, icon: Icons.pool),
      ],
    );
  }
}

The flutter tutorial  is a website that bring you the latest and amazing resources of code. All the languages codes are included in this website. The languages like flutter, android, java,kotlin etc.with the help of this languages any user can develop the beautiful application

For more information about Flutter. visit www.fluttertutorial.in