dart 为什么我的showDateDialog()函数没有改变Flutter中按钮的Text()?

13z8s7eq  于 2023-06-19  发布在  Flutter
关注(0)|答案(1)|浏览(118)

我有一个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]);
              },
            ),
          ],
        );
      },
    );
mf98qq94

mf98qq941#

您必须使用有状态小部件中的按钮来实现这一点,这样它们就可以自己更新自己的状态。只需使用有状态小部件的按钮,如下面的示例。

import 'dart:typed_data';

import 'package:flutter/material.dart';
import 'package:flutter_maps/utils/image_helper.dart';

class PlayPauseButton extends StatefulWidget {
  final Function(bool) togglePlayPause;
  final bool initialIsPlaying = false;

  const PlayPauseButton({Key? key, required this.togglePlayPause})
      : super(key: key);

  @override
  PlayPauseButtonState createState() => PlayPauseButtonState();
}

class PlayPauseButtonState extends State<PlayPauseButton> {
  late bool isPlaying;
  late Future<Uint8List> playIconFuture;
  late Future<Uint8List> pauseIconFuture;

  Uint8List? playIcon;
  Uint8List? pauseIcon;

  @override
  void initState() {
    super.initState();
    isPlaying = widget.initialIsPlaying;
    loadIcons();
  }

  Future<void> loadIcons() async {
    playIconFuture = ImageHelper.loadImage('assets/images/play_button.png', 100);
    pauseIconFuture = ImageHelper.loadImage('assets/images/pause_button.png', 100);

    playIcon = null;
    pauseIcon = null;

    final List<Uint8List> images = await Future.wait([playIconFuture, pauseIconFuture]);
    setState(() {
      playIcon = images[0];
      pauseIcon = images[1];
    });
  }

  void togglePlayPause() {
    setState(() {
      isPlaying = !isPlaying;
    });
  }

  @override
  Widget build(BuildContext context) {
    return (pauseIcon != null && playIcon != null)
    ? IconButton(
      onPressed: () {
        togglePlayPause(); //Altera o estado do isPlaying localmente
        widget.togglePlayPause(isPlaying); //Altera o estado do isPlaying no widget pai
      },
      icon: isPlaying
          ? Image.memory(pauseIcon!, fit: BoxFit.contain)
          : Image.memory(playIcon!, fit: BoxFit.contain),
    )
    : const CircularProgressIndicator();
  }
}

相关问题