Change Switch Background Color
Complete Code For Change Switch Background Color In Flutter
main.dart
import 'package:flutter/material.dart';
void main() => runApp(new MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
@override
State<StatefulWidget> createState() => MyHomePageState();
}
class MyHomePageState extends State<MyHomePage> {
bool _isSwitched = true;
List<Color> _colors = [
Colors.teal, Colors.pink, Colors.orange, Colors.brown, Colors.black
];
int _currentIndex = 1;
_onChanged() {
int _colorCount = _colors.length;
setState(() {
if (_currentIndex == _colorCount - 1) {
_currentIndex = 0;
} else {
_currentIndex += 1;
}
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.amber[500],
title: Text("Change Switch Color"),
),
body: Column(
children: <Widget>[
Expanded(
child: Center(
child: Switch(
onChanged: (val) => setState(() => _isSwitched = val),
activeColor: _colors[_currentIndex],
value: _isSwitched,
),
),
),
Expanded(
child: Center(
child: RaisedButton(
onPressed: _onChanged,
child: Text("Change Color"),
color: Colors.amber[500],
textColor: Colors.white,
),
),
),
],
),
);
}
}