En este ejemplo voy a mostrar cómo crear un select de opciones en Flutter en el lenguaje de programación Dart.
Para ello vamos a crear un componente que vamos a llamar en este caso CustomSelect. Este elemento o componente, tendrá sus propiedades y eventos para manejar la selección de opciones, y así, poder usarlo en cualquier vista o Widget.
import 'package:flutter/material.dart';
class CustomSelect extends StatefulWidget {
final List<String> options;
final String? selectedOption;
final ValueChanged<String>? onChanged;
const CustomSelect({
Key? key,
required this.options,
this.selectedOption,
this.onChanged,
}) : super(key: key);
@override
_CustomSelectState createState() => _CustomSelectState();
}
class _CustomSelectState extends State<CustomSelect> {
late String _selectedOption;
@override
void initState() {
super.initState();
_selectedOption = widget.selectedOption ?? widget.options.first;
}
@override
Widget build(BuildContext context) {
return DropdownButton<String>(
value: _selectedOption,
onChanged: (String? newValue) {
if (newValue != null) {
setState(() {
_selectedOption = newValue;
});
widget.onChanged?.call(newValue);
}
},
items: widget.options.map<DropdownMenuItem<String>>((String value) {
return DropdownMenuItem<String>(
value: value,
child: Text(value),
);
}).toList(),
);
}
}
Ahora, en la vista MyApp, usaremos este componente CustomSelect que acabamos de crear como muestro a continuación.
import 'package:flutter/material.dart';
import 'package:your_package_name/custom_select.dart'; // Importa el componente
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: SelectExample(), // Usa la vista SelectExample
);
}
}
class SelectExample extends StatefulWidget {
@override
_SelectExampleState createState() => _SelectExampleState();
}
class _SelectExampleState extends State<SelectExample> {
final List<String> _options = ['Option 1', 'Option 2', 'Option 3'];
late String _selectedOption;
@override
void initState() {
super.initState();
_selectedOption = _options.first;
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Select Example'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
CustomSelect(
options: _options,
selectedOption: _selectedOption,
onChanged: (String newValue) {
setState(() {
_selectedOption = newValue;
});
},
),
SizedBox(height: 20),
Text(
'Selected option: $_selectedOption',
style: TextStyle(fontSize: 18),
),
],
),
),
);
}
}
Por último, observamos a continuación el resultado del ejemplo completo.
Espero que les sirva de ayuda. ¡Que tengan un feliz día!

