diff --git a/example/lib/main.dart b/example/lib/main.dart index 07c259a..fecec1f 100644 --- a/example/lib/main.dart +++ b/example/lib/main.dart @@ -8,22 +8,18 @@ class MyApp extends StatelessWidget { Widget build(BuildContext context) { return MaterialApp( debugShowCheckedModeBanner: false, - theme: ThemeData( - primarySwatch: Colors.deepOrange - ), + theme: ThemeData(primarySwatch: Colors.deepOrange), home: HomeScreen(), ); } } - class HomeScreen extends StatefulWidget { @override _HomeScreenState createState() => _HomeScreenState(); } class _HomeScreenState extends State { - bool status = false; @override @@ -46,11 +42,21 @@ class _HomeScreenState extends State { }); }, ), - SizedBox(height: 12.0,), - Text('Value : $status', style: TextStyle( - color: Colors.black, - fontSize: 20.0 - ),) + SizedBox( + height: 12.0, + ), + Text( + 'Value : $status', + style: TextStyle(color: Colors.black, fontSize: 20.0), + ), + RaisedButton( + child: Text("change switch"), + onPressed: () { + setState(() { + status = !status; + }); + }, + ) ], ), ), diff --git a/lib/custom_switch.dart b/lib/custom_switch.dart index c9cf4bf..f631260 100644 --- a/lib/custom_switch.dart +++ b/lib/custom_switch.dart @@ -6,22 +6,22 @@ class CustomSwitch extends StatefulWidget { final bool value; final ValueChanged onChanged; final Color activeColor; - final Color inactiveColor = Colors.grey; - final String activeText = 'On'; - final String inactiveText = 'Off'; - final Color activeTextColor = Colors.white70; - final Color inactiveTextColor = Colors.white70; + final Color inactiveColor; + final String activeText; + final String inactiveText; + final Color activeTextColor; + final Color inactiveTextColor; - const CustomSwitch({ - Key key, - this.value, - this.onChanged, - this.activeColor, - this.inactiveColor, - this.activeText, - this.inactiveText, - this.activeTextColor, - this.inactiveTextColor}) + const CustomSwitch( + {Key key, + this.value, + this.onChanged, + this.activeColor, + this.inactiveColor = Colors.grey, + this.activeText = 'On', + this.inactiveText = 'Off', + this.activeTextColor = Colors.white70, + this.inactiveTextColor = Colors.white70}) : super(key: key); @override @@ -52,11 +52,6 @@ class _CustomSwitchState extends State builder: (context, child) { return GestureDetector( onTap: () { - if (_animationController.isCompleted) { - _animationController.reverse(); - } else { - _animationController.forward(); - } widget.value == false ? widget.onChanged(true) : widget.onChanged(false); @@ -116,4 +111,18 @@ class _CustomSwitchState extends State }, ); } + + @override + void didUpdateWidget(CustomSwitch oldWidget) { + super.didUpdateWidget(oldWidget); + + if (oldWidget.value == widget.value) { + return; + } + if (_animationController.isCompleted) { + _animationController.reverse(); + } else { + _animationController.forward(); + } + } }