我有一个showDateDialog()函数,让用户点击一个按钮选择一个时刻,首先选择日期,然后选择小时和分钟。它不会更改按钮的Text()的值,但会更改变量的值。
当我确认我选择的日期时,我希望按钮改变它的文本,但它只改变了变量,文本保持不变,即使使用setState(({})。
下面的函数是在一个“类GoogleMapsState extends State”里面的,变量是在它外面的
DateTime selectedStartDate = DateTime.now().subtract(const Duration(hours: 12));
DateTime selectedEndDate = DateTime.now();
//Função para pegar o dia e a hora por meio de widgets específicos
void showDateDialog() async {
final startHour = selectedStartDate.hour;
final startMinute = selectedStartDate.minute;
final endHour = selectedEndDate.hour;
final endMinute = selectedEndDate.minute;
final selectedDates = await showDialog<List<DateTime>>(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: const Center(child: Text('Informe o período do histórico desejado')),
content: Column(
mainAxisSize: MainAxisSize.min,
children: [
const Text('Data inicial'),
Row(
children: [
Expanded(
child: ElevatedButton(
child: Text("${selectedStartDate.day}/${selectedStartDate.month}/${selectedStartDate.year}, às ${selectedStartDate.hour}:${selectedStartDate.minute}"),
onPressed: () async {
await pickDate(selectedStartDate).then((date) async => {
if(date != null) {//Se não clicar em cancelar e a data for definida
await pickTime(TimeOfDay(hour: startHour, minute: startMinute)).then((time) => {
if(time != null) {
setState(() {
selectedStartDate = DateTime(
date.year,
date.month,
date.day,
time.hour,
time.minute,
);
SnackBarHelper.showSnackBar(context, "Atualizou o valor: $selectedStartDate");
})
}
}),
}
});
},
),
),
],
),
const SizedBox(height: 16),
const Text('Data final'),
Row(
children: [
Expanded(
child: ElevatedButton(
child: Text("${selectedEndDate.day}/${selectedEndDate.month}/${selectedEndDate.year}, às ${selectedEndDate.hour}:${selectedEndDate.minute}"),
onPressed: () async {
await pickDate(selectedEndDate).then((date) async => {
if(date != null) {//Se não clicar em cancelar e a data for definida
await pickTime(TimeOfDay(hour: endHour, minute: endMinute)).then((time) => {
if(time != null) {
setState(() {
selectedEndDate = DateTime(
date.year,
date.month,
date.day,
time.hour,
time.minute,
);
})
}
}),
}
});
},
),
),
],
),
],
),
actions: [
TextButton(
child: const Text('Cancelar'),
onPressed: () {
Navigator.of(context).pop();
},
),
ElevatedButton(
child: const Text('Confirmar'),
onPressed: () {
trackingStartMoment = selectedStartDate;
trackingEndMoment = selectedEndDate;
SnackBarHelper.showSnackBar(context, "Data inicial: ${trackingStartMoment.day}/${trackingStartMoment.month}/${trackingStartMoment.year}, às ${trackingStartMoment.hour}:${trackingStartMoment.minute}");
SnackBarHelper.showSnackBar(context, "Data final: ${trackingEndMoment.day}/${trackingEndMoment.month}/${trackingEndMoment.year}, às ${trackingEndMoment.hour}:${trackingEndMoment.minute}");
Navigator.of(context).pop([selectedStartDate, selectedEndDate]);
},
),
],
);
},
);
1条答案
按热度按时间mf98qq941#
您必须使用有状态小部件中的按钮来实现这一点,这样它们就可以自己更新自己的状态。只需使用有状态小部件的按钮,如下面的示例。