Switch in Flutter

18-Sep-2024

Learn how to use the Switch widget to create toggle buttons for user preferences in Flutter

A switch widget creates a toggle button that allows the user to switch between two states.
Typically represents an on/off or true/false scenario.

There Are Some Common Attributes for switch

valuevalue property represents the current state of the switch
onChanged The onChanged callback is triggered when the switch is toggled, and it updates the _isSwitched state accordingly.

Here's a simple example of using a switch in Flutter:

File open lib->main.dart file −



import 'package:flutter/material.dart';

void main() {
runApp(
MyApp()
);
}
class MyApp extends StatefulWidget{

@override
_MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
bool _isSwitch = false;

void _handleRadioValueChanged(bool value) {
setState(() {
_isSwitch = value;
});
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
backgroundColor: Colors.blue,
title: Text('Switch Example',
style:TextStyle(fontSize: 20,color: Colors.white)),
),
body:
Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Switch(
value: _isSwitch,
onChanged: _handleRadioValueChanged),
SizedBox(height: 16.0),
Text('Selected Option: ${_isSwitch ? 'on' : 'off'}')
],
),
),
));

}
}






Open Device Manager, run the emulator, and then run the application. Next, check the working output and check the output you declared in your code.


Output:


Comments