| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126 |
- 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<UploadPage> createState() => _UploadPageState();
- }
- class _UploadPageState extends State<UploadPage> {
- 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<void> _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('退出'),
- ),
- ],
- ],
- ),
- ),
- ),
- );
- }
- }
|