我正在尝试创建一个可以下载图像的应用程序。我想在按下“下载”按钮时显示一个带有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
显示弹出对话框。 _key
下面用于管理弹出窗口,类似地,您可以将另一个key
传递到Text(...)
以更改其状态,例如Downloading
或Download Completed
。
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
用于Show
或hide
创建的对话框。
为了简单起见,将类中的GlobalKey
初始化为GlobalKey<State> _dialogKey = GlobalKey<State>();
。
然后您可以将对话框显示为:
showLoadingDialog(context, _dialogKey);
并且当您希望隐藏它时,只需致电:
Navigator.of(_dialogKey.currentContext,rootNavigator: true).pop();
希望这会有所帮助。