Home > Software design >  How to create styled switch on Flutter?
How to create styled switch on Flutter?

Time:05-18

I am making a VPN app. I stuck on start button. I want to create switch button loke that. How can I create animated switch like that on Flutter? Please help.
Styled switch

CodePudding user response:

Here is my_stylish_switch.dart

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:vpn/core/style/palette.dart';

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

  @override
  State<VPNSwitch> createState() => _VPNSwitchState();
}

class _VPNSwitchState extends State<VPNSwitch> {
  bool isConnected = false;
  toggleVpn() => setState(() => isConnected = !isConnected);

  @override
  Widget build(BuildContext context) {
    Size _size = MediaQuery.of(context).size;
    var switchHeight = _size.height * 0.2;
    var switchWidth = _size.width * 0.2;
    double switchBorderRadius = 20;
    return Container(
      padding: const EdgeInsets.all(5),
      decoration: BoxDecoration(
          color: Palette.kOuterSwitch,
          borderRadius: BorderRadius.circular(switchBorderRadius)),
      child: Container(
          width: switchWidth,
          height: switchHeight,
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(switchBorderRadius),
            color: Palette.kInnerSwitch,
          ),
          child: Stack(
            children: [
              Positioned(
                left: 0,
                right: 0,
                top: 25,
                child: Column(
                  children: [
                    Icon(CupertinoIcons.chevron_up, color: Colors.white),
                    Icon(CupertinoIcons.chevron_up, color: Colors.white),
                  ],
                ),
              ),
              AnimatedAlign(
                duration: const Duration(milliseconds: 500),
                alignment:
                    isConnected ? Alignment.topCenter : Alignment.bottomCenter,
                child: InkWell(
                  onTap: () => toggleVpn(),
                  child: AnimatedContainer(
                      width: switchWidth,
                      height: switchHeight / 2,
                      duration: const Duration(milliseconds: 500),
                      decoration: BoxDecoration(
                          borderRadius:
                              BorderRadius.circular(switchBorderRadius),
                          color: Palette.kSwitchSlide),
                      child: Icon(
                        Icons.power_settings_new_rounded,
                        color: isConnected ? Colors.green : Colors.red,
                      )),
                ),
              ),
            ],
          )),
    );
  }
}
  • Related