Change the Color of a Switch - FormBuilderSwitch - flutter

I want to change the Color for the Switch if normal an if switched. In the Material.dart I find some stuff but cannot write it right. If you could do some examples that would be great. Thank you

FormBuilderSwitch(
                  name: "public",
                  title: Text("Wird noch ein Mitspieler gesucht?"),
                  initialValue: widget.event?.public ?? false,
                  controlAffinity: ListTileControlAffinity.leading,
                  decoration: InputDecoration(border: InputBorder.none),
                ),

Upvotes: 1

Views: 6686

Answers (1)

Adithaz
Adithaz

Reputation: 419

You can use bool to do that

Example:

bool switched = false; //Based on which state you want it to be on init

Widget to trigger switch function

FormBuilderSwitch(
                        onChanged: (bool) {
                          setState(() {
                            bool = !bool;
                            switched = bool;
                          });
                        },
                      )

and here's an example of color change based on bool

Container(
   color: switched? Colors.white : Colors.blue,
)

Update :

Here's the code

FormBuilderSwitch(
              name: "public",
              title: Text("Wird noch ein Mitspieler gesucht?"),
              initialValue: false,
              controlAffinity: ListTileControlAffinity.leading,
              decoration: InputDecoration(border: InputBorder.none),
              onChanged: (bool) {
                setState(() {
                  bool = !bool;
                  switched = bool;
                });
              },
            ),
            Container(
              height: 20, 
              width: 20, 
              color: switched ? Colors.black54 : Colors.blue,
            ),

The outputs

https://i.sstatic.net/x3j35.png

https://i.sstatic.net/XUBpy.png

Update:

FormBuilderSwitch(
                  name: "public",
                  title: Text("Wird noch ein Mitspieler gesucht?"),
                  initialValue: false,
                  controlAffinity: ListTileControlAffinity.leading,
                  activeColor: Colors.red
                  decoration: InputDecoration(border: InputBorder.none),
                  onChanged: (bool) {
                    setState(() {
                      bool = !bool;
                      switched = bool;
                    });
                  },
                ),
                Container(
                  height: 20, 
                  width: 20, 
                  color: switched ? Colors.red : Colors.black,
                ),

Upvotes: 4

Related Questions