Switch in Kotlin KMP KMM Compose Multiplatform

In today’s tutorial, we will learn Switch in Kotlin KMP KMM Compose Multiplatform for both Android & iOS platforms. We will learn about the customization of Switch, the properties of the Switch, and Switch events.

Switch in Kotlin KMP KMM Compose Multiplatform

Switch in Kotlin KMP KMM Compose Multiplatform:

Switches are used to enable toggle functionality in mobile and web applications. We can enable and disable modes and switch between dark and light modes with switches. It enables the mobile app’s functionality to Turn ON and OFF on a specific case.

Creating Switch in KMP(KMM):

To create a Switch in KMP, we would define the Switch widget in Composable.

Code explanation:

  • switchState: The mutable state that handles the Button enable and Disable state in the form of True and False.
  • checked: The default value of Switch should be the same as the mutable state.
  • onCheckedChange: Invokes when the user Turns ON and OFF switches.

Complete source code:

Screenshot:

Switch in KMP

Adding Label to Switch:

To add a label with Switch, we have to wrap both Switch and Text into the Row widget. To set the padding between both of them, I am using the Spacer widget.

Screenshot:

Switch with label in KMP KMM

Customizing Switch Colors:

The Switch component has the property SwitchDefaults.colors() with multiple sub-properties, which can customize the Swith UI.

  1. checkedThumbColor: Set the Switch thumb color when the Switch is in the ON state.
  2. uncheckedThumbColor: Set thumb color when the Switch is in the OFF state.
  3. checkedTrackColor: Set the switch track color when it is ON.
  4. uncheckedTrackColor: Set the switch track color to OFF.
  5. disabledCheckedThumbColor: Set the color of the thumb when the switch is ON but disabled.
  6. disabledCheckedTrackColor: Set the track color when the switch is ON but disabled.
  7. disabledUncheckedThumbColor: Set the color of the thumb in the switch OFF and disabled.
  8. disabledUncheckedTrackColor: Set the track color when the switch is OFF and disabled.
  9. uncheckedTrackAlpha: To set the opacity of Track when the switch is OFF.
  10. checkedTrackAlpha: Adjust the opacity of the track when the Switch is ON.

Screenshot:

Switch in Kotlin KMP KMM Compose Multiplatform

 

Create Disabled Switch:

To Enable and Disable a Switch, we have to use the enabled property.

  • enabled = true: To Enable the switch.
  • enabled = false: To Disable the Switch.

Screenshot:

Disabled Switch in KMP KMM

 

Retrieve Switch ON and OFF Value in Text:

We are creating a Text widget showing the Switch ON and OFF result in Text using an IF condition with Switch state.

Screenshot in Android device:

Switch OFF Android Switch ON Android

Screenshot in iOS device:

Switch in KMP iOS iOS Switch

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *