dreampad/lib/app/shared/widgets/update_dialog.dart

95 lines
2.5 KiB
Dart
Raw Normal View History

2023-11-28 10:44:58 +08:00
import 'dart:io';
import 'package:app_installer/app_installer.dart';
import 'package:dio/dio.dart';
import 'package:flustars_flutter3/flustars_flutter3.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:dreampad/app/shared/constants/constants.dart';
class UpdateDialog extends StatefulWidget {
const UpdateDialog({
super.key,
required this.url,
});
final String url;
@override
State<UpdateDialog> createState() => _UpdateDialogState();
}
class _UpdateDialogState extends State<UpdateDialog> {
final CancelToken _cancelToken = CancelToken();
double _value = 0;
@override
void initState() {
super.initState();
download(widget.url);
}
@override
void dispose() {
if (!_cancelToken.isCancelled && _value != 1) {
_cancelToken.cancel();
}
super.dispose();
}
@override
Widget build(BuildContext context) {
final Color primaryColor = Theme.of(context).primaryColor;
return Container(
height: 168.h,
width: 468.w,
padding: REdgeInsets.symmetric(horizontal: 18.0, vertical: 18.0),
decoration: BoxDecoration(
color: Colors.transparent,
borderRadius: BorderRadius.circular(9.0).r,
),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
LinearProgressIndicator(
minHeight: 30.h,
backgroundColor: Colors.white,
valueColor: AlwaysStoppedAnimation<Color>(primaryColor),
value: _value,
),
Gaps.vGap8,
Text('新版本下载中...', style: TextStyles.mediumWhite18),
],
),
);
}
Future<void> download(url) async {
try {
DirectoryUtil.createStorageDirSync(category: 'download');
final String path = DirectoryUtil.getStoragePath(
category: 'download', fileName: 'dreampad', format: 'apk')!;
final File file = File(path);
await Dio().download(
url,
file.path,
cancelToken: _cancelToken,
onReceiveProgress: (int count, int total) {
if (total != -1) {
setState(() {
_value = count / total;
});
if (count == total) {
SmartDialog.dismiss();
AppInstaller.installApk(path);
}
}
},
);
// ignore: empty_catches
} catch (e) {}
}
}