Skip to content

Instantly share code, notes, and snippets.

@alexrintt
Last active February 21, 2023 22:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alexrintt/6c4ab5c547f7b7a5a0821d7dc9962485 to your computer and use it in GitHub Desktop.
Save alexrintt/6c4ab5c547f7b7a5a0821d7dc9962485 to your computer and use it in GitHub Desktop.
Flutter Material 3 switch sample for a StackOverflow question https://stackoverflow.com/questions/75526521/how-to-customize-flutter-material-3-switch.
// Copyright (c) 2019, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
debugShowCheckedModeBanner: false,
theme: ThemeData.dark(
useMaterial3: true,
).copyWith(
scaffoldBackgroundColor: Colors.black,
),
home: const MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
final String title;
const MyHomePage({
Key? key,
required this.title,
}) : super(key: key);
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
bool _value = false;
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Switch(
focusColor: Colors.blue,
trackColor: MaterialStateProperty.resolveWith(
(Set<MaterialState> states) {
if (states.contains(MaterialState.selected)) {
return Colors.red;
}
return Colors.red.withOpacity(.1);
},
),
overlayColor: MaterialStateProperty.resolveWith(
(Set<MaterialState> states) {
if (states.contains(MaterialState.disabled)) {
return Colors.red;
}
return Colors.white.withOpacity(.1);
},
),
hoverColor: Colors.green,
thumbColor: MaterialStateProperty.resolveWith(
(Set<MaterialState> states) {
if (states.contains(MaterialState.selected)) {
return HSLColor.fromColor(Colors.red)
.withLightness(0.2)
.toColor();
}
return Colors.red;
},
),
splashRadius: 24,
inactiveTrackColor: Colors.pink,
activeTrackColor: Colors.green,
thumbIcon: MaterialStateProperty.resolveWith(
(Set<MaterialState> states) {
if (states.contains(MaterialState.selected)) {
return const Icon(Icons.check, color: Colors.red);
}
return null;
},
),
activeColor: Colors.lime,
inactiveThumbColor: Colors.orange,
value: _value,
onChanged: (bool value) => setState(() => _value = !_value),
),
),
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment