Switch in Flutter

Create Free Backend With Appwrite

Introduction

The Switch widget in Flutter is a fundamental UI component used for toggling between two states, such as on/off or true/false. This article will guide you through various implementations of the Switch widget, from basic usage to more advanced scenarios including custom styling and integration with forms.

Example 1: Basic Switch

Learn how to create a simple switch that toggles a boolean value.

Switch(
  value: isSwitched,
  onChanged: (value) {
    setState(() {
      isSwitched = value;
    });
  },
),
Run Online

Example 2: Custom Styled Switch

Customize the appearance of a switch with custom colors.

Switch(
  value: isSwitched,
  activeTrackColor: Colors.lightGreenAccent,
  activeColor: Colors.green,
  onChanged: (value) {
    setState(() {
      isSwitched = value;
    });
  },
)
Run Online

Example 3: Switch List

Implement a list of switches, each controlling a different setting.

var settings = <String, bool>{
  'Wi-Fi': true,
  'Bluetooth': false,
  'Airplane Mode': false,
  'Mobile Data': true,
};

ListView(
  children: settings.keys.map((String key) {
    return SwitchListTile(
      title: Text(key),
      value: settings[key]!,
      onChanged: (bool value) {
        setState(() {
          settings[key] = value;
        });
      },
    );
  }).toList(),
)
Run Online

Example 4: Form Switch

Incorporate a switch into a form to accept terms & conditions or toggle preferences.

Form(
  child: Column(
    children: [
      SwitchListTile(
        title: Text("Accept Terms & Conditions"),
        value: isAccepted,
        onChanged: (bool value) {
          setState(() {
            isAccepted = value;
          });
        },
      ),
      // Other form elements
    ],
  ),
)
Run Online

Example 5: Profile Visibility Switch

Use a switch to control the visibility of user profile information.

SwitchListTile(
  title: Text('Show Profile Publicly'),
  value: isProfilePublic,
  onChanged: (bool value) {
    setState(() {
      isProfilePublic = value;
    });
  },
)
Run Online

Challenge

Create a settings page using switches to control various app features such as notifications, dark mode, location tracking, and automatic updates.

// App settings options
Map<String, bool> appSettings = {
  'Notifications': true,
  'Dark Mode': false,
  'Location Tracking': true,
  'Automatic Updates': false,
};