颤动警报对话框未从函数外部更新

时间:2021-06-17 10:23:58

标签: flutter flutter-alertdialog

我想在警报对话框内制作一个下载进度消息,但状态不在模态内更新 这是使用dio的下载功能

downloadBook() async {
    Directory tempDir = await getTemporaryDirectory();
    var response = await dio.download(widget.bookModel.acf.bookLink,
        tempDir.path + '/books/' + widget.bookModel.title.rendered + '.epub',
        options: Options(
          responseType: ResponseType.bytes,
        ), onReceiveProgress: (actualbytes, totalbytes) {
      var percenatge = actualbytes / totalbytes * 100;
      _percentageBar = percenatge / 100;
      setState(() {
        downloadMessage = 'Downloading... ${percenatge.floor()} %';
      });
    });
  }

这是警报对话功能

void _showDialog(BuildContext context) {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: new Text("Alert!!"),
          content: new Text(downloadMessage),
          actions: <Widget>[
            new FlatButton(
              child: new Text("OK"),
              onPressed: () {
                Navigator.of(context).pop();
              },
            ),
          ],
        );
      },
    );
  }

我在文本按钮内进行了这样的调用,但消息停留在 0% 且未更新;

onPressed: () {
        // _showDialog(context);
        downloadBook();
        showDialog(
          context: context,
          builder: (context) {
            String contentText = "Content of Dialog";
            return StatefulBuilder(
              builder: (context, setState) {
                return AlertDialog(
                  title: new Text("Alert!!"),
                  content: new Text(downloadMessage),
                  actions: <Widget>[
                    new FlatButton(
                      child: new Text("OK"),
                      onPressed: () {
                        Navigator.of(context).pop();
                      },
                    ),
                  ],
                );
              },
            );
          },
        );
      },

2 个答案:

答案 0 :(得分:0)

你可以使用

<块引用>

StatefullBuilder

小部件顶部的警报对话框并通过

<块引用>

设置状态

到你调用它的地方。

通过这种方式,您可以从外部访问 State。

答案 1 :(得分:0)

正如我从您的问题中了解到的,您正在尝试为您的警报对话框设置不同的状态,因此我只会更新您关于 alertDialog 的代码,然后您就可以执行您想要的操作。

showDialog(
  context: context,
  builder: (context) {
    String contentText = "Content of Dialog";
    return StatefulBuilder(
      builder: (context, setState) {
        return AlertDialog(
          title: new Text("Alert!!"),
          content: new Text(downloadMessage),
          actions: <Widget>[
            new FlatButton(
              child: new Text("OK"),
              onPressed: () {
                Navigator.of(context).pop();
              },
            ),
          ],
        );
      },
    );
  },
);

所以你可以使用 setState 来处理你想要的任何进度。