Skip to content

Commit cb50d8f

Browse files
add tests, improve logic
1 parent c19a1e6 commit cb50d8f

2 files changed

Lines changed: 70 additions & 2 deletions

File tree

lib/flutter_switch.dart

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -173,11 +173,12 @@ class _FlutterSwitchState extends State<FlutterSwitch>
173173
super.initState();
174174
_animationController = AnimationController(
175175
vsync: this,
176+
value: widget.value ? 1.0 : 0.0,
176177
duration: Duration(milliseconds: 60),
177178
);
178179
_toggleAnimation = AlignmentTween(
179-
begin: widget.value ? Alignment.centerRight : Alignment.centerLeft,
180-
end: widget.value ? Alignment.centerLeft : Alignment.centerRight,
180+
begin: Alignment.centerLeft,
181+
end: Alignment.centerRight,
181182
).animate(
182183
CurvedAnimation(parent: _animationController, curve: Curves.linear),
183184
);

test/flutter_switch_test.dart

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
import 'package:flutter/material.dart';
2+
import 'package:flutter_test/flutter_test.dart';
3+
4+
import '../lib/flutter_switch.dart';
5+
6+
void main() {
7+
testWidgets(
8+
"displays the toggle indicator on the right if the given value is true",
9+
(WidgetTester tester) async {
10+
await tester.pumpWidget(
11+
_FlutterSwitchTestbed(
12+
value: true,
13+
),
14+
);
15+
16+
final align = tester.widget<Align>(find.byType(Align));
17+
18+
expect(align.alignment, equals(Alignment.centerRight));
19+
},
20+
);
21+
22+
testWidgets(
23+
"displays the toggle indicator on the left if the given value is false",
24+
(WidgetTester tester) async {
25+
await tester.pumpWidget(
26+
_FlutterSwitchTestbed(
27+
value: false,
28+
),
29+
);
30+
31+
final align = tester.widget<Align>(find.byType(Align));
32+
33+
expect(align.alignment, equals(Alignment.centerLeft));
34+
},
35+
);
36+
}
37+
38+
/// A testbed needed to test the switch widget.
39+
class _FlutterSwitchTestbed extends StatelessWidget {
40+
/// A callback that is called when the switch is toggled.
41+
final ValueChanged<bool> onToggle;
42+
43+
/// An initial value of the switch.
44+
final bool value;
45+
46+
/// A default on toggle callback of the switch.
47+
static void _defaultOnToggle(bool value) {}
48+
49+
/// Creates a new instance of this testbed.
50+
const _FlutterSwitchTestbed({
51+
Key key,
52+
this.onToggle = _defaultOnToggle,
53+
this.value,
54+
}) : super(key: key);
55+
56+
@override
57+
Widget build(BuildContext context) {
58+
return MaterialApp(
59+
home: Scaffold(
60+
body: FlutterSwitch(
61+
value: value,
62+
onToggle: (value) => {},
63+
),
64+
),
65+
);
66+
}
67+
}

0 commit comments

Comments
 (0)