我想在文本框中显示日期选择器,并在文本框中删除所选日期。
要选择日期,我使用可点击的图像和在文本字段中设置的所选日期,但是我无法从文本字段中删除该日期。
Widget build(BuildContext context) {
return Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
LightText(
text: ' ${widget.labelTxt}',
),
Padding(
padding: EdgeInsets.only(top: 3),
),
Container(
height: 24,
padding: EdgeInsets.only(left: 5),
decoration: BoxDecoration(borderRadius: BorderRadius.circular(3)),
child: Theme(
data: ThemeData(hintColor: lightGrey),
child: TextField(
enabled: isEditForInputField
? !widget.enableVal ? false : true
: false,
controller: widget.controllerText,
keyboardType: TextInputType.number,
decoration: InputDecoration(
suffix: GestureDetector(
onTap: (){
isEditForInputField
? _selectDate(context, widget.value,
widget.firebaseKey, widget.index)
: null;
},
child: Padding(
padding: const EdgeInsets.only(top: 7.0, right: 3.0,),
child: Image.asset('assets/images/calendar.png',
height: 25.0,
width: 25.0,
),
),
),
disabledBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.grey),
),
border: OutlineInputBorder(),
contentPadding: const EdgeInsets.symmetric(
vertical: 3.0, horizontal: 5.0)),
),
),
),
],
),
答案 0 :(得分:0)
我认为您应该尝试这个。
按如下所示创建小部件
Column(
children: <Widget>[
Container(
color: Colors.grey[300],
margin: EdgeInsets.all(10.0),
padding: EdgeInsets.all(10.0),
width: double.infinity,
child: GestureDetector(
onTap: () {
openDatePicker(dateValue);
},
child: Row(
children: <Widget>[
Expanded(
flex: 9,
child: Text(dateValue),
),
Expanded(
flex: 1,
child: Icon(Icons.calendar_today),
),
],
),
),
),
],
),
将此代码添加到有状态的小部件中,
String dateValue = "Select Date";
DateTime selectedDate = DateTime.now();
openDatePicker(initialDateString) async {
var initialDate = convertToDate(initialDateString) ?? selectedDate;
initialDate =
(initialDate.year >= 1900 && initialDate.isBefore(selectedDate)
? initialDate
: selectedDate);
final DateTime pickedDate = await showDatePicker(
context: context,
initialDate: initialDate,
firstDate: DateTime(2018, 1),
lastDate: DateTime(3000),
);
if (pickedDate != null && pickedDate != selectedDate) {
setState(() {
selectedDate = pickedDate;
dateValue = new DateFormat.yMd().format(pickedDate);
});
}
}
DateTime convertToDate(String input) {
try {
var d = new DateFormat.yMd().parseStrict(input);
return d;
} catch (e) {
return null;
}
}
@override
void initState() {
super.initState();
dateValue = new DateFormat.yMd().format(selectedDate);
}
您现在可以轻松地管理日期。如果要从文本中删除选定的日期,请创建另一个小部件,例如IconButton或其他适合您的部件。然后,将该小部件的onPress将dateValue设置为空,并设置小部件的状态。
这将为您提供帮助。