gpt4 book ai didi

flutter - 当我按下下载按钮时,如何显示带有CircularProgressIndicator的弹出窗口和下载状态

转载 作者:行者123 更新时间:2023-12-03 04:47:40 24 4
gpt4 key购买 nike

我正在尝试创建一个可以下载图像的应用程序。我想在按下“下载”按钮时显示一个带有CircularProgressIndicator和“下载状态”的弹出窗口。每当我按下“下载”按钮时,图像就会在后台下载,但它不会在屏幕上显示任何内容。

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:path_provider/path_provider.dart';

class HomePage extends StatefulWidget {
@override
_HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
final imgUrl =
'https://images.unsplash.com/photo-1503023345310-bd7c1de61c7d?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&w=1000&q=80';
bool downloading = false;
var progressString = " ";

@override
void initState() {
super.initState();
downloadFile();
}

// Downloading image using Dio package
Future<void> downloadFile() async {
Dio dio = Dio();
try {
var dir = await getApplicationDocumentsDirectory();
await dio.download(imgUrl, "${dir.path}/DownloadedImage.jpg",
onReceiveProgress: (rec, total) {
print("rec: $rec, total: $total");
setState(() {
downloading = true;
progressString = ((rec / total) * 100).toStringAsFixed(0) + "%";
});
});
} catch (e) {
print(e);
}

setState(() {
progressString = "Download Completed";
downloading = false;
});
}

@override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Center(
child: RaisedButton.icon(
onPressed: () {
downloadFile();
},
icon: Icon(Icons.file_download),
label: Text('Download'),
color: Colors.blueAccent,
),
)
],
)),
);
}
}

我想在按下按钮时显示此容器
  Container(
height: 120.0,
width: 200.0,
child: Card(
color: Colors.black54,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
CircularProgressIndicator(),
SizedBox(
height: 10.0,
),
Text('Downloading $progressString'),
],
),
),
);

最佳答案

您可以使用showDialog显示一个弹出对话框。

static Future showDialog(BuildContext context, GlobalKey _key) async   {
return showLoadingDialog(
context: context,
barrierDismissible: false,
builder: (BuildContext context){
return SimpleDialog(
key: _key,
children: <Widget>[
Center(
child: Container(
child: Row(
children: <Widget>[
CircularProgressIndicator(),
SizedBox(
height:10,
width:10,
),
Text("Please Wait!"),
]
),
],
),
);
}
);
}

此处 GlobalKey用于对创建的对话框进行 Showhide

为了简单地调用它,请将类中的 GlobalKey初始化为 GlobalKey<State> _dialogKey = GlobalKey<State>();

然后,您可以将对话框显示为:
showLoadingDialog(context, _dialogKey);

当您希望隐藏它时,只需调用:
Navigator.of(_dialogKey.currentContext,rootNavigator: true).pop();

希望这可以帮助。

关于flutter - 当我按下下载按钮时,如何显示带有CircularProgressIndicator的弹出窗口和下载状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62003522/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com