How to Create a Switch in Flutter: Simple Guide
In Flutter, you create a switch using the
Switch widget, which requires a value to show its state and an onChanged callback to update that state. You typically manage the switch state with a boolean variable inside a StatefulWidget.Syntax
The Switch widget has two main properties:
- value: a boolean that shows if the switch is ON (
true) or OFF (false). - onChanged: a function called when the user toggles the switch, receiving the new boolean value.
You must manage the switch state yourself, usually inside a StatefulWidget.
dart
Switch(
value: isSwitched,
onChanged: (bool newValue) {
setState(() {
isSwitched = newValue;
});
},
)Output
A toggle switch that changes between ON and OFF states when tapped.
Example
This example shows a complete Flutter app with a switch that toggles a boolean state and updates the UI text accordingly.
dart
import 'package:flutter/material.dart'; void main() => runApp(MyApp()); class MyApp extends StatefulWidget { @override State<MyApp> createState() => _MyAppState(); } class _MyAppState extends State<MyApp> { bool isSwitched = false; @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar(title: Text('Flutter Switch Example')), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Switch( value: isSwitched, onChanged: (bool newValue) { setState(() { isSwitched = newValue; }); }, ), Text(isSwitched ? 'Switch is ON' : 'Switch is OFF'), ], ), ), ), ); } }
Output
A screen with a switch and text below it that says 'Switch is OFF' initially and changes to 'Switch is ON' when toggled.
Common Pitfalls
Common mistakes when using Switch include:
- Not managing the switch state in a
StatefulWidget, so the UI does not update. - Passing a
nullor constant value tovalue, making the switch unresponsive. - Not calling
setState()insideonChanged, so the switch does not visually toggle.
dart
/* Wrong: Using StatelessWidget and no state update */ Switch( value: false, onChanged: (bool newValue) { // No setState, UI won't update }, ); /* Right: Use StatefulWidget and setState */ setState(() { isSwitched = newValue; });
Quick Reference
Remember these tips when using Switch in Flutter:
- Always use a
StatefulWidgetto hold the switch state. - Use
valueto show the current state. - Use
onChangedto update the state withsetState(). - The switch is a simple toggle UI element for boolean values.
Key Takeaways
Use the Switch widget with a boolean value and onChanged callback to create a toggle.
Manage the switch state inside a StatefulWidget using setState to update UI.
Avoid using Switch in StatelessWidget without state management to prevent UI issues.
Always call setState inside onChanged to reflect changes visually.
Switch is ideal for simple ON/OFF user choices in Flutter apps.