top of page

Flutter Switch

Updated: Nov 27, 2022

Flutter Switch is a material design widget. We can use it as a toggle button. It can hold only two values:- true or false. Whenever the switch is toggled, the onChanged function is called. The onChanged function does not maintain the state, rather if any change is found in the widgets following its value, the widget is rebuilt.

Here is the syntax for Switch Widget.

Switch(value: value, onChanged: onChanged)
  • value: The value is of data type boolean and asks for the value you want the switch to display.

  • onChanged: As discussed, it is a callback function and contains the current value of Switch. If you want, you can set the new value to the value parameter by using a variable.

Here is an example.

Switch(
  value: currentValue,
  onChanged: (value) => setState(
    () => currentValue = value,
  ),
),


We can change the Switch widget by modifying the following parameters.

  • activeColor: This parameter asks for a colour to be displayed on the thumb when the switch is on.

  • activeThumbImage: This asks for the image to be displayed on the thumb of Switch when the Switch is on.

  • activeTrackColor: Similar to activeColor, this displays the colour on the track instead of the thumb colour.

  • inactiveThumbColor: This parameter asks for a colour to be displayed on the thumb when the switch is off.

  • inactiveThumbImage: This asks for the image to be displayed on the thumb of Switch when the Switch is off.

  • inactiveTrackColor: Similar to inactiveColor, this displays the colour on the track instead of the thumb colour.

Here is another example.

Switch(
  value: currentValue,
  onChanged: (value) => setState(
    () => currentValue = value,
  ),
  activeColor: Colors.green,
  activeTrackColor: Colors.greenAccent,
  inactiveThumbColor: Colors.red,
  inactiveTrackColor: Colors.redAccent,
),


Don't stop learning. There are more tutorials here. If you have any doubt, comment below or contact me using the contact form.



Related Posts

See All

The image sharing apps, shopping apps, etc. have image zoom functionality required to see the image in detail. Today, we will learn to implement the same with the help of a widget, InteractiveViewer.

bottom of page