| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259 |
- import 'package:chicken_farm/core/services/offline_storage_service.dart';
- import 'package:chicken_farm/core/services/upload_service.dart';
- import 'package:chicken_farm/core/utils/logger.dart';
- import 'package:chicken_farm/core/utils/service_checker.dart';
- import 'package:flutter/material.dart';
- import 'package:go_router/go_router.dart';
- class UploadPage extends StatefulWidget {
- const UploadPage({super.key});
- @override
- State<UploadPage> createState() => _UploadPageState();
- }
- // 定义状态常量
- class UploadStatus {
- static const int preparing = 0; // 准备上传
- static const int uploading = 1; // 正在上传
- static const int completed = 2; // 上传完成
- static const int error = 3; // 上传出错
- static const int exception = 4; // 上传异常
- }
- class _UploadPageState extends State<UploadPage> with WidgetsBindingObserver {
- late UploadService _uploadService;
- int _totalOperations = 0;
- int _uploadedOperations = 0;
- int _status = UploadStatus.preparing; // 改为int类型
- bool _isUploading = false;
- bool _uploadCompleted = false;
- @override
- void initState() {
- super.initState();
- _uploadService = UploadService();
- logger.d('UploadPage initState');
- WidgetsBinding.instance.addObserver(this);
- // 初始化时就开始上传
- WidgetsBinding.instance.addPostFrameCallback((_) {
- _startUpload();
- });
- }
- @override
- void dispose() {
- WidgetsBinding.instance.removeObserver(this);
- super.dispose();
- }
- @override
- void didChangeAppLifecycleState(AppLifecycleState state) async {
- super.didChangeAppLifecycleState(state);
- //
- final pendingOps = await OfflineStorageService().getPendingOperations();
- final pendingCount = pendingOps.length;
- if (pendingCount > 0) {
- logger.d('有$pendingCount个待上传数据');
- _registerUploadCallbacks();
- }
- }
- // 根据状态获取对应的文本
- String _getStatusText() {
- switch (_status) {
- case UploadStatus.preparing:
- return '准备上传...';
- case UploadStatus.uploading:
- return '数据上传中...';
- case UploadStatus.completed:
- return '上传完成';
- case UploadStatus.error:
- return '上传出错,请稍后再试';
- case UploadStatus.exception:
- return '上传异常,请稍后再试';
- default:
- return '未知状态';
- }
- }
- // 根据状态获取对应的文本样式
- TextStyle _getStatusTextStyle(BuildContext context) {
- switch (_status) {
- case UploadStatus.completed:
- return Theme.of(
- context,
- ).textTheme.headlineSmall!.copyWith(color: Colors.green);
- case UploadStatus.error:
- case UploadStatus.exception:
- return Theme.of(
- context,
- ).textTheme.headlineSmall!.copyWith(color: Colors.red);
- default:
- return Theme.of(context).textTheme.headlineSmall!;
- }
- }
- Future<void> _startUpload() async {
- logger.d('准备上传');
- // 检查网络
- if (!await ServiceChecker().checkService()) {
- setState(() {
- _isUploading = false;
- _status = UploadStatus.error; // 使用状态常量
- });
- return;
- }
- // 开始上传
- try {
- _uploadService.showUpload();
- _registerUploadCallbacks();
- await _uploadService.startUpload();
- } catch (e) {
- logger.e(e);
- setState(() {
- _isUploading = false;
- _status = UploadStatus.exception; // 使用状态常量
- });
- }
- }
- void _registerUploadCallbacks() {
- _uploadService.showUpload();
- setState(() {
- _isUploading = true;
- _status = UploadStatus.uploading; // 使用状态常量
- _uploadedOperations = 0;
- _totalOperations = 0;
- _uploadCompleted = false;
- });
- int t = DateTime.now().millisecondsSinceEpoch;
- logger.d('开始上传,$t');
- // 注册回调
- _uploadService.registerCallbacks(
- onProgress: (uploaded, total, status) {
- if (mounted) {
- setState(() {
- _uploadedOperations = uploaded;
- _totalOperations = total;
- // 进度更新时不改变状态码,保持uploading状态
- });
- }
- logger.d('上传进度 $t:$uploaded/$total');
- },
- onComplete: () {
- if (mounted) {
- setState(() {
- _isUploading = false;
- _uploadCompleted = true;
- _status = UploadStatus.completed; // 使用状态常量
- });
- }
- logger.d('上传完成');
- },
- onError: (message) {
- logger.e('上传出错:$message');
- if (mounted) {
- setState(() {
- _isUploading = false;
- _status = UploadStatus.error; // 使用状态常量
- });
- }
- },
- );
- }
- @override
- Widget build(BuildContext context) {
- return PopScope(
- canPop: false, // 禁用返回键
- onPopInvokedWithResult: (bool didPop, Object? result) {
- // 返回键被触发时的回调,但因为 canPop 为 false,所以不会真正返回
- },
- child: Scaffold(
- appBar: AppBar(
- title: const Text('数据上传'),
- centerTitle: true,
- automaticallyImplyLeading: false, // 禁用默认的返回图标
- ),
- body: LayoutBuilder(
- builder: (context, constraints) {
- return SingleChildScrollView(
- child: ConstrainedBox(
- constraints: BoxConstraints(minHeight: constraints.maxHeight),
- child: IntrinsicHeight(
- child: Center(
- child: Padding(
- padding: const EdgeInsets.all(16.0),
- child: Column(
- mainAxisAlignment: MainAxisAlignment.center,
- crossAxisAlignment: CrossAxisAlignment.center,
- children: [
- Text(
- _getStatusText(), // 使用方法获取状态文本
- style: _getStatusTextStyle(context), // 使用方法获取样式
- textAlign: TextAlign.center,
- ),
- const SizedBox(height: 30),
- if (_totalOperations > 0) ...[
- LinearProgressIndicator(
- value: _uploadedOperations / _totalOperations,
- minHeight: 10,
- ),
- const SizedBox(height: 10),
- Text('$_uploadedOperations / $_totalOperations'),
- const SizedBox(height: 30),
- ],
- if (_isUploading) ...[
- const SizedBox(
- width: 50,
- height: 50,
- child: CircularProgressIndicator(),
- ),
- const SizedBox(height: 20),
- SizedBox(
- width: 120,
- child: ElevatedButton(
- onPressed: () {
- _uploadService.hideUpload();
- context.pop(2); // 后台上传
- },
- child: const Text('后台上传'),
- ),
- ),
- ] else if (_uploadCompleted) ...[
- SizedBox(
- width: 120,
- child: ElevatedButton(
- onPressed: () {
- context.pop(1); // 上传成功
- },
- child: const Text('返回'),
- ),
- ),
- ] else ...[
- SizedBox(
- width: 120,
- child: ElevatedButton(
- onPressed: () {
- context.pop(0); // 取消上传
- },
- child: const Text('退出'),
- ),
- ),
- ],
- ],
- ),
- ),
- ),
- ),
- ),
- );
- },
- ),
- ),
- );
- }
- }
|