import 'package:chicken_farm/core/services/upload_service.dart'; import 'package:flutter/material.dart'; import 'package:go_router/go_router.dart'; class UploadPage extends StatefulWidget { const UploadPage({super.key}); @override State createState() => _UploadPageState(); } class _UploadPageState extends State { late UploadService _uploadService; int _totalOperations = 0; int _uploadedOperations = 0; String _status = '准备上传...'; bool _isUploading = false; bool _uploadCompleted = false; @override void initState() { super.initState(); _uploadService = UploadService(); _startUpload(); } Future _startUpload() async { setState(() { _isUploading = true; _status = '开始上传...'; }); try { await _uploadService.uploadPendingOperations( context: context, // 传递 context 给 upload service onProgress: (uploaded, total, status) { setState(() { _uploadedOperations = uploaded; _totalOperations = total; _status = status; }); }, onComplete: () { setState(() { _isUploading = false; _uploadCompleted = true; _status = '上传完成'; }); }, onError: (message) { setState(() { _isUploading = false; _status = '上传出错: $message'; }); }, ); } catch (e) { setState(() { _isUploading = false; _status = '上传异常: ${e.toString()}'; }); } } // 后台上传 void _backgroundUpload() { // 返回上一页并传递false表示后台上传 context.pop(false); } @override Widget build(BuildContext context) { return PopScope( canPop: !_isUploading, // 只有在不上传时才能返回 child: Scaffold( appBar: AppBar( title: const Text('数据上传'), automaticallyImplyLeading: false, // 禁用返回按钮 ), body: Padding( padding: const EdgeInsets.all(16.0), child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Text( _status, style: Theme.of(context).textTheme.headlineSmall, 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) ...[ ElevatedButton( onPressed: _backgroundUpload, child: const Text('后台上传'), ), ] else if (_uploadCompleted) ...[ ElevatedButton( onPressed: () { context.pop(true); // 返回上一页并传递结果 }, child: const Text('返回'), ), ] else ...[ ElevatedButton( onPressed: () { context.pop(false); // 返回上一页并传递结果 }, child: const Text('退出'), ), ], ], ), ), ), ); } }