Sin duda una de las sorpresas que tuve el otro día fue encontrarme que no hay un componente en Flutter para mostrar una fecha y ser integrado en un formulario.
Vamos a ver lo simple que es hacer esto en Flutter para un caso muy concreto cuyo resultado es el siguiente.
Para ello necesitaremos solo 3 sencillos pasos.
Construir Picker habilitado
Tendremos una Row con el Texto a mostrar, y el icono que muestre que se pueda hacer click sobre ella. Además lo metemos dentro de un InputDecorator y un InkWell para que tenga aspecto de TextFormField.
Widget _getDatePickerEnabled() { | |
return InkWell( | |
onTap: () { | |
_selectDate(context); | |
}, | |
child: InputDecorator( | |
decoration: InputDecoration(labelText: _labelText, enabled: true), | |
child: Row( | |
mainAxisAlignment: MainAxisAlignment.spaceBetween, | |
mainAxisSize: MainAxisSize.max, | |
children: <Widget>[ | |
Text( | |
DateFormat.yMMMd().format(_dateSelected), | |
style: CustomTheme.of(context).textTheme.subhead.copyWith(), | |
), | |
Icon(Icons.arrow_drop_down, | |
color: Theme.of(context).brightness == Brightness.light | |
? Colors.grey.shade700 | |
: Colors.white70), | |
], | |
), | |
), | |
); | |
} |
Construir Picker deshabilitado
Aquí yo utilizo un TextField que tenga estilo disabled.
Widget _getDatePickerDisabled() { | |
return CustomTextField( | |
enabled: false, | |
labelText: _labelText, | |
initialValue: DateFormat.yMMMd().format(_dateSelected)); | |
} |
Evento para seleccionar la fecha
Nuestro _getDatePickerEnabled al hacer onTap llama a _selectDate que simplemente hará uso de la función que viene en Material showDatePicker que muestra un Dialog con un calendario.
Future<void> _selectDate(BuildContext context) async { | |
final DateTime picked = await showDatePicker( | |
context: context, | |
initialDate: _dateSelected, | |
firstDate: new DateTime(minYear), | |
lastDate: new DateTime(maxYear)); | |
if (picked != null && _onDateChange != null) { | |
_onDateChange(picked); | |
} | |
} |
Como veis es muy sencillo hacer componentes que aún no están incluidos en Flutter sin la necesidad de instalar ninguna dependencia.
Espero que os sirva y para cualquier duda podéis escribirme en mi Twitter.
Top comments (1)
Muy sencillo, gracias por el aporte.