pikapika/lib/screens/DownloadImportScreen.dart

162 lines
3.9 KiB
Dart

import 'dart:io';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
import 'package:pikapika/basic/Channels.dart';
import 'package:pikapika/basic/Common.dart';
import 'package:pikapika/basic/Method.dart';
import 'package:pikapika/basic/config/ChooserRoot.dart';
import 'components/ContentLoading.dart';
import 'components/RightClickPop.dart';
// 导入
class DownloadImportScreen extends StatefulWidget {
const DownloadImportScreen({Key? key}) : super(key: key);
@override
State<StatefulWidget> createState() => _DownloadImportScreenState();
}
class _DownloadImportScreenState extends State<DownloadImportScreen> {
bool _importing = false;
String _importMessage = "";
@override
void initState() {
registerEvent(_onMessageChange, "EXPORT");
super.initState();
}
@override
void dispose() {
unregisterEvent(_onMessageChange);
super.dispose();
}
void _onMessageChange(event) {
if (event is String) {
setState(() {
_importMessage = event;
});
}
}
@override
Widget build(BuildContext context) {
return rightClickPop(
child: buildScreen(context),
context: context,
canPop: !_importing,
);
}
Widget buildScreen(BuildContext context) {
if (_importing) {
return Scaffold(
body: ContentLoading(label: _importMessage),
);
}
List<Widget> actions = [];
if (Platform.isWindows ||
Platform.isMacOS ||
Platform.isLinux ||
Platform.isAndroid) {
actions.add(_fileImportButton());
}
actions.add(_networkImportButton());
return Scaffold(
appBar: AppBar(
title: const Text('导入'),
),
body: ListView(
children: [
Container(
padding: const EdgeInsets.all(10),
child: Text(_importMessage),
),
...actions,
],
),
);
}
Widget _fileImportButton() {
return MaterialButton(
height: 80,
onPressed: () async {
late String chooseRoot;
try {
chooseRoot = await currentChooserRoot();
} catch (e) {
defaultToast(context, "$e");
return;
}
var ls = await FilePicker.platform.pickFiles(
dialogTitle: '选择要导入的文件',
allowMultiple: false,
initialDirectory: chooseRoot,
type: FileType.custom,
allowedExtensions: ['zip'],
allowCompression: false,
);
String? path = ls != null && ls.count > 0 ? ls.paths[0] : null;
if (path != null) {
try {
setState(() {
_importing = true;
});
await method.importComicDownload(path);
setState(() {
_importMessage = "导入成功";
});
} catch (e) {
setState(() {
_importMessage = "导入失败 $e";
});
} finally {
setState(() {
_importing = false;
});
}
}
},
child: const Text('选择zip文件进行导入'),
);
}
Widget _networkImportButton() {
return MaterialButton(
height: 80,
onPressed: () async {
var path =
await inputString(context, '请输入导出设备提供的地址\n例如 "192.168.1.2:50000"');
if (path != null) {
try {
setState(() {
_importing = true;
});
await method.importComicDownloadUsingSocket(path);
setState(() {
_importMessage = "导入成功";
});
} catch (e) {
setState(() {
_importMessage = "导入失败 $e";
});
} finally {
setState(() {
_importing = false;
});
}
}
},
child: const Text('从其他设备导入'),
);
}
}