Created
September 4, 2023 02:58
-
-
Save Sp4Rx/09656671606aa12a3ebdce35378e9fc7 to your computer and use it in GitHub Desktop.
Switch Button Stateless
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'package:flutter/material.dart'; | |
void main() { | |
runApp(MyApp()); | |
} | |
class MyApp extends StatelessWidget { | |
@override | |
Widget build(BuildContext context) { | |
return MaterialApp( | |
home: SwitchButtonWrapper(), | |
); | |
} | |
} | |
class SwitchButtonWrapper extends StatefulWidget { | |
@override | |
State<SwitchButtonWrapper> createState() => _SwitchButtonWrapperState(); | |
} | |
class _SwitchButtonWrapperState extends State<SwitchButtonWrapper> { | |
bool isSwitched = false; | |
void toggleSwitch() { | |
setState(() { | |
isSwitched = !isSwitched; | |
}); | |
} | |
@override | |
Widget build(BuildContext context) { | |
return Scaffold( | |
appBar: AppBar( | |
title: const Text('Switch Button Stateless'), | |
), | |
body: Center( | |
child: Column( | |
mainAxisAlignment: MainAxisAlignment.center, | |
children: <Widget>[ | |
SwitchButton( | |
isSwitched: isSwitched, | |
onPressed: toggleSwitch, | |
), | |
], | |
), | |
), | |
); | |
} | |
} | |
class SwitchButton extends StatelessWidget { | |
final bool isSwitched; | |
final VoidCallback onPressed; | |
const SwitchButton({required this.isSwitched, required this.onPressed}); | |
@override | |
Widget build(BuildContext context) { | |
return Column( | |
mainAxisAlignment: MainAxisAlignment.center, | |
children: <Widget>[ | |
AnimatedContainer( | |
duration: const Duration(milliseconds: 300), | |
width: 100.0, | |
height: 40.0, | |
alignment: isSwitched ? Alignment.centerRight : Alignment.centerLeft, | |
decoration: BoxDecoration( | |
borderRadius: BorderRadius.circular(20.0), | |
color: isSwitched ? Colors.green : Colors.red, | |
), | |
child: Text( | |
isSwitched ? 'Enable' : 'Disable', | |
style: const TextStyle( | |
color: Colors.white, | |
fontWeight: FontWeight.bold, | |
), | |
), | |
), | |
const SizedBox(height: 20.0), | |
GestureDetector( | |
onTap: onPressed, | |
child: Container( | |
width: 60.0, | |
height: 30.0, | |
decoration: BoxDecoration( | |
borderRadius: BorderRadius.circular(20.0), | |
color: Colors.grey, | |
), | |
child: AnimatedAlign( | |
duration: const Duration(milliseconds: 300), | |
alignment: | |
isSwitched ? Alignment.centerRight : Alignment.centerLeft, | |
child: Container( | |
width: 30.0, | |
height: 30.0, | |
decoration: const BoxDecoration( | |
shape: BoxShape.circle, | |
color: Colors.white, | |
), | |
), | |
), | |
), | |
), | |
], | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment