MD MEHEDI HASAN
MD MEHEDI HASAN

Reputation: 2490

How to create custom switch in flutter?

Flutter provides a default switch. But I want to customize it accordingly to my UI. How can customized flutter default switch?

enter image description here

Upvotes: 0

Views: 5901

Answers (2)

Mezo
Mezo

Reputation: 49

i was looking for a way to implement a custom switch but i only found the answer on this one that doesn't use a package.

i thought it is too complicated so i made this one instead it is essentially the same but a bit simpler and i wanted to share it.

FYI i made the colors hardcoded feel free to send them as trackColors, thumbColors. active and inactive it will animate that as well as many other aspects animatedContainers are indeed awesome.

class StyledSwitch extends StatefulWidget {
  final void Function(bool isToggled) onToggled;

  const StyledSwitch({Key? key, required this.onToggled}) : super(key: key);

  @override
  State<StyledSwitch> createState() => _StyledSwitchState();
}

class _StyledSwitchState extends State<StyledSwitch> {
  bool isToggled = false;
  double size = 30;
  double innerPadding = 0;

  @override
  void initState() {
    innerPadding = size / 10;
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () {
        setState(() => isToggled = !isToggled);
        widget.onToggled(isToggled);
      },
      onPanEnd: (b) {
        setState(() => isToggled = !isToggled);
        widget.onToggled(isToggled);
      },
      child: AnimatedContainer(
        height: size,
        width: size * 2,
        padding: EdgeInsets.all(innerPadding),
        alignment: isToggled ? Alignment.centerLeft : Alignment.centerRight,
        duration: const Duration(milliseconds: 300),
        curve: Curves.easeOut,
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(50),
          color: isToggled ? Colors.blue.shade100 : Colors.grey.shade300,
        ),
        child: Container(
          width: size - innerPadding * 2,
          height: size - innerPadding * 2,
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(100),
            color: isToggled ? Colors.blue.shade600 : Colors.grey.shade500,
          ),
        ),
      ),
    );
  }
}

this is an output test

Upvotes: 3

MD MEHEDI HASAN
MD MEHEDI HASAN

Reputation: 2490

For a custom switch. I used this class. Custom switch class

You can customize the height and width of the switch, the border radius of the switch, the colors, the toggle size, etc.

Upvotes: 1

Related Questions