1 | // Copyright 2014 The Flutter Authors. All rights reserved. |
---|---|
2 | // Use of this source code is governed by a BSD-style license that can be |
3 | // found in the LICENSE file. |
4 | |
5 | import 'package:flutter/material.dart'; |
6 | |
7 | /// Flutter code sample for [Switch]. |
8 | |
9 | void main() => runApp(const SwitchApp()); |
10 | |
11 | class SwitchApp extends StatelessWidget { |
12 | const SwitchApp({super.key}); |
13 | |
14 | @override |
15 | Widget build(BuildContext context) { |
16 | return MaterialApp( |
17 | home: Scaffold( |
18 | appBar: AppBar(title: const Text('Switch Sample')), |
19 | body: const Center(child: SwitchExample()), |
20 | ), |
21 | ); |
22 | } |
23 | } |
24 | |
25 | class SwitchExample extends StatefulWidget { |
26 | const SwitchExample({super.key}); |
27 | |
28 | @override |
29 | State<SwitchExample> createState() => _SwitchExampleState(); |
30 | } |
31 | |
32 | class _SwitchExampleState extends State<SwitchExample> { |
33 | bool light = true; |
34 | |
35 | @override |
36 | Widget build(BuildContext context) { |
37 | // This object sets amber as the track color when the switch is selected. |
38 | // Otherwise, it resolves to null and defers to values from the theme data. |
39 | const WidgetStateProperty<Color?> trackColor = WidgetStateProperty<Color?>.fromMap( |
40 | <WidgetStatesConstraint, Color>{WidgetState.selected: Colors.amber}, |
41 | ); |
42 | // This object sets the track color based on two WidgetState attributes. |
43 | // If neither state applies, it resolves to null. |
44 | final WidgetStateProperty<Color?> overlayColor = WidgetStateProperty<Color?>.fromMap( |
45 | <WidgetState, Color>{ |
46 | WidgetState.selected: Colors.amber.withOpacity(0.54), |
47 | WidgetState.disabled: Colors.grey.shade400, |
48 | }, |
49 | ); |
50 | |
51 | return Switch( |
52 | // This bool value toggles the switch. |
53 | value: light, |
54 | overlayColor: overlayColor, |
55 | trackColor: trackColor, |
56 | thumbColor: const WidgetStatePropertyAll<Color>(Colors.black), |
57 | onChanged: (bool value) { |
58 | // This is called when the user toggles the switch. |
59 | setState(() { |
60 | light = value; |
61 | }); |
62 | }, |
63 | ); |
64 | } |
65 | } |
66 |