How To Change Background Color Of Switch In Flutter App

admin_img Posted By Bajarangi soft , Posted On 27-11-2020

The switch itself does not maintain any state. Instead, when the state of the switch changes, the widget calls the onChanged callback. Most widgets that use a switch will listen for the onChanged callback and rebuild the switch with a new value to update the visual appearance of the switch.

How To Change Background Color Of Switch In Flutter App

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,
              ),
            ),
          ),
        ],
      ),
    );
  }
}

Related Post