The Switch widget allows users to turn on or off any setting in your app. For example, you could use it on a settings page to enable/disable push notifications, location services, etc.
Let's see how to add a switch widget and build an example that shows its value on a Text widget. Here's how it looks:
Showing switch value
Here is a simple way to do it:
- First, click on the + Add Widget, drag the Switch widget from the Base Elements tab, or add it directly from the widget tree.
- Below the Switch, add a Text widget, move to the properties panel, click on Set from Variable and choose the Widget State > switchValue (i.e., name of your switch).
Adding switch widget
You might want to show the switch with a default status, i.e., ON or OFF. For example, showing the location service setting with a default switch OFF.
To set the initial value:
- Select the Switch widget, move to the properties panel, and see the Switch Initial Value property.
- Use the checkbox to set this value manually, or click Set from Variable to set it based on the dynamic value. If you choose Set from Variable, ensure you pass the boolean value from the source (e.g., API response, Firestore document field).
Setting initial value
You might want to save the switch value as soon as it is toggled ON or OFF. For example, saving in a local state variable or Firestore document field. You can do so by adding the action on the switch widget.
The switch widget provides you with the following types of actions (aks callbacks), which you can use to add actions under it.
- 1.On Toggled On: Actions added under this will be triggered whenever the switch is ON.
- 2.On Toggled Off: Actions added under this will be triggered whenever the switch is OFF.
Here's how you do it:
- Select the Switch widget, select Actions from the Properties panel (the right menu), and click Open. This will open an Action flow Editor in a new popup window.
- Select On Toggled On or On Toggled Off and add an action that will update the value. (e.g., update local state, update Firestore record, etc.)
Saving switch value
You can customize the appearance and behavior of this widget using the various properties available under the properties panel.
To change the switch colors:
- Select the Switch widget, move to the properties panel, and scroll down to the Switch Properties section. Here you can change the color for the following properties:
- Active Color: The color of the thumb (circle) when the switch is ON.
- Active Track Color: The color of a track (the line over which the circle slides) when the switch is ON.
- Inactive Track Color: The color of a track (the line over which the circle slides) when the switch is OFF.
- Inactive Thumb Color: The color of the thumb (circle) when the switch is OFF.