我有一个按钮列表。 onPressed函数触发datePicker函数,选择日期后,按钮的文本应更改为选择的日期。每个日期都保存到DateTime值列表(“日期”)中,我稍后使用。我已经初始化buttonText并将其在initState中的值设置为'date'。问题是,在选择日期之后,每个按钮都显示相同的日期。
Future<DateTime> _pickDate() async {
DateTime chosen = DateTime.now();
DateTime date = await showDatePicker(
context: context,
initialDate: pickedDate,
firstDate: DateTime(DateTime.now().year - 100),
lastDate: DateTime.now());
if (date != null) {
setState(() {
chosen = date;
print(chosen);
dates.add(chosen);
print(dates);
});
}
return chosen;
}
Widget _dateList() {
return Container(
margin: EdgeInsets.all(10),
width: MediaQuery.of(context).size.width * 0.8,
height: MediaQuery.of(context).size.height * 0.1,
decoration: BoxDecoration(
//border: Border.all(
// color: Colors.red
// )
),
child: ListView.builder(
scrollDirection: Axis.horizontal,
shrinkWrap: true,
itemCount:
pregController.text == '' ? 0 : int.parse(pregController.text),
itemBuilder: (BuildContext context, int index) {
DateTime birth = DateTime.now();
return Container(
padding: EdgeInsets.all(5),
width: MediaQuery.of(context).size.width * 0.3,
child: RaisedButton(
color: Colors
.primaries[Random().nextInt(Colors.primaries.length)],
key: Key(index.toString()),
child: Text(
buttonText,
textAlign: TextAlign.center,
style: GoogleFonts.lato(
textStyle: TextStyle(
color: Colors.white,
)),
),
onPressed: () async {
birth = await _pickDate();
setState(() {
buttonText =
'${dates[index].day}/${dates[index].month}/${dates[index].year}';
});
}),
);
}),
);
}