Switch
O Switch no Flutter é um widget que representa um botão de alternância entre dois estados (ligado/desligado, ativo/inativo, etc.). Os usuários podem alternar entre esses estados tocando no widget. Aqui está um exemplo básico de como usar o Switch:
class MySwitchWidget extends StatefulWidget {
@override
_MySwitchWidgetState createState() => _MySwitchWidgetState();
}
class _MySwitchWidgetState extends State<MySwitchWidget> {
bool _switchValue = false; // Estado inicial do Switch
@override
Widget build(BuildContext context) {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Switch(
value: _switchValue, // Valor atual do Switch (ligado ou desligado)
onChanged: (newValue) {
// Função chamada quando o valor do Switch é alterado
setState(() {
_switchValue = newValue;
});
},
),
Text('Switch está ${_switchValue ? 'ligado' : 'desligado'}'),
],
);
}
}
void main() => runApp(MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Flutter Switch Example'),
),
body: Center(
child: MySwitchWidget(),
),
),
));
Neste exemplo, _switchValue representa o estado atual do Switch. Quando o usuário toca no Switch para alterná-lo, a função onChanged é chamada e atualiza o _switchValue. O Switch representa visualmente o estado ligado (true) ou desligado (false) com base no valor de _switchValue.
O Switch é útil quando você deseja permitir que os usuários alternem uma configuração específica no seu aplicativo, como ativar ou desativar uma funcionalidade.
