Flutter文件下载插件tbib_downloader的使用
Flutter文件下载插件tbib_downloader的使用
插件简介
tbib_downloader
是一个用于在Flutter应用程序中下载文件并打开它的插件。它可以显示通知和进度条,并能接收下载字节数和总字节数。
注意事项
- 此插件使用
awesome_notifications
来展示通知。 - iOS上不支持通知进度条功能。
iOS配置步骤
第一步
修改Xcode项目设置:
将 BUILD_LIBRARY_FOR_DISTRIBUTION = YES
改为
BUILD_LIBRARY_FOR_DISTRIBUTION = NO
第二步
在 info.plist
文件中添加以下内容:
<key>LSSupportsOpeningDocumentsInPlace</key>
<true/>
<key>UIFileSharingEnabled</key>
<true/>
使用方法
初始化插件
在应用入口处初始化插件:
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await TBIBDownloader().init();
runApp(MyApp());
}
添加通知监听器
在主页面的 initState()
方法中添加通知监听器:
@override
void initState() {
super.initState();
AwesomeNotifications().setListeners(
onActionReceivedMethod: MyNotificationService.onActionReceivedMethod,
onNotificationCreatedMethod: MyNotificationService.onNotificationCreatedMethod,
onNotificationDisplayedMethod: MyNotificationService.onNotificationDisplayedMethod,
onDismissActionReceivedMethod: MyNotificationService.onDismissActionReceivedMethod,
);
}
创建通知服务类
创建一个名为 MyNotificationService
的类来处理通知事件:
class MyNotificationService {
static Future<void> onNotificationCreatedMethod(ReceivedNotification receivedNotification) async {
// 处理通知创建逻辑
}
static Future<void> onNotificationDisplayedMethod(ReceivedNotification receivedNotification) async {
// 处理通知显示逻辑
}
static Future<void> onDismissActionReceivedMethod(ReceivedAction receivedAction) async {
// 处理通知关闭逻辑
}
static Future<void> onActionReceivedMethod(ReceivedAction receivedAction) async {
if (receivedAction.buttonKeyPressed == 'tbib_downloader_open_file') {
var res = await TBIBDownloaderOpenFile().openFile(path: receivedAction.payload!['path']!);
log(res.message);
} else if (receivedAction.buttonKeyPressed == 'tbib_downloader_delete_file') {
await TBIBDownloaderOpenFile().deleteFile(receivedAction.payload!['path']!);
}
}
}
下载文件示例
使用 ElevatedButton
触发下载操作,同时可以实时更新下载进度:
ElevatedButton(
onPressed: () async {
var path = await TBIBDownloader().downloadFile(
url: 'http://212.183.159.230/50MB.zip',
fileName: 'dummy.zip',
directoryName: 'test',
onReceiveProgress: ({int? receivedBytes, int? totalBytes}) {
if (!context.mounted) return;
setState(() {
progress = (receivedBytes! / totalBytes!);
});
},
);
debugPrint('path $path');
if (!context.mounted) return;
setState(() {
progress = 0;
});
},
child: const Text('download'),
),
完整示例代码
下面是一个完整的Flutter应用示例,包含了上述所有配置:
import 'package:awesome_notifications/awesome_notifications.dart';
import 'package:flutter/material.dart';
import 'package:tbib_downloader/tbib_downloader.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await TBIBDownloader().init();
runApp(const App());
}
class App extends StatelessWidget {
const App({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Background downloader',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MainPage(),
);
}
}
class MainPage extends StatefulWidget {
const MainPage({super.key});
@override
State<MainPage> createState() => _MainPageState();
}
class _MainPageState extends State<MainPage> {
double progress = 0;
@override
void initState() {
super.initState();
AwesomeNotifications().setListeners(
onActionReceivedMethod: MyNotificationService.onActionReceivedMethod,
onNotificationCreatedMethod: MyNotificationService.onNotificationCreatedMethod,
onNotificationDisplayedMethod: MyNotificationService.onNotificationDisplayedMethod,
onDismissActionReceivedMethod: MyNotificationService.onDismissActionReceivedMethod,
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Download File'),
),
body: Column(
children: [
if (progress > 0)
Align(
alignment: Alignment.topCenter,
child: LinearProgressIndicator(value: progress),
),
Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
ElevatedButton(
onPressed: () async {
var path = await TBIBDownloader().downloadFile(
url: 'https://ash-speed.hetzner.com/1GB.bin',
receiveBytesAsMB: true,
fileName: 'remittance_report.pdf',
directoryName: 'pdf',
disabledShareFileButton: true,
);
},
child: const Text('Download Large File'),
),
const SizedBox(height: 20),
ElevatedButton(
onPressed: () async {
var path = await TBIBDownloader().downloadFile(
url: 'https://file-examples.com/storage/fef44df12666d835ba71c24/2017/10/file-sample_150kB.pdf',
fileName: 'dummy1.pdf',
saveFileInDataApp: true,
directoryName: 'test',
);
debugPrint('path $path');
},
child: const Text('Download Small File'),
),
const SizedBox(height: 20),
ElevatedButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => const SecondPage()),
);
},
child: const Text('Go to Second Page'),
),
],
)
],
),
);
}
}
// Notification Service Class
class MyNotificationService {
static Future<void> onNotificationCreatedMethod(ReceivedNotification receivedNotification) async {
// Handle notification creation logic here
}
static Future<void> onNotificationDisplayedMethod(ReceivedNotification receivedNotification) async {
// Handle notification display logic here
}
static Future<void> onDismissActionReceivedMethod(ReceivedAction receivedAction) async {
// Handle notification dismissal logic here
}
static Future<void> onActionReceivedMethod(ReceivedAction receivedAction) async {
if (receivedAction.buttonKeyPressed == 'tbib_downloader_open_file') {
var res = await TBIBDownloaderOpenFile().openFile(path: receivedAction.payload!['path']!);
log(res.message);
} else if (receivedAction.buttonKeyPressed == 'tbib_downloader_delete_file') {
await TBIBDownloaderOpenFile().deleteFile(receivedAction.payload!['path']!);
}
}
}
class SecondPage extends StatelessWidget {
const SecondPage({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Second Page'),
),
body: const Center(
child: Text('This is the second page.'),
),
);
}
}
以上就是关于 tbib_downloader
插件的详细介绍和使用指南,希望能帮助你顺利地在项目中集成文件下载功能。如果有任何问题或需要进一步的帮助,请随时提问!
更多关于Flutter文件下载插件tbib_downloader的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter文件下载插件tbib_downloader的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
当然,以下是如何在Flutter项目中使用tbib_downloader
插件进行文件下载的示例代码。tbib_downloader
是一个强大的Flutter插件,用于在Android和iOS平台上下载文件。
1. 添加依赖
首先,你需要在pubspec.yaml
文件中添加tbib_downloader
依赖:
dependencies:
flutter:
sdk: flutter
tbib_downloader: ^最新版本号 # 请替换为实际最新版本号
然后运行flutter pub get
来获取依赖。
2. 导入插件
在你的Dart文件中导入tbib_downloader
插件:
import 'package:tbib_downloader/tbib_downloader.dart';
3. 初始化下载器
在应用启动时或需要下载文件前,初始化下载器:
void initDownloader() async {
// 初始化下载管理器
await Downloader().initialize(
context: context, // 当前上下文
requestCode: 1024, // 自定义请求码
);
}
4. 配置权限
在AndroidManifest.xml
和Info.plist
中配置必要的权限。
AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
Info.plist
在iOS项目中,你需要在Info.plist
中添加以下权限配置(通过Xcode):
NSAppTransportSecurity
- 允许任意网络请求NSFileHandlingUsageDescription
- 允许应用访问文件系统
5. 下载文件
以下是一个完整的下载文件示例:
import 'package:flutter/material.dart';
import 'package:tbib_downloader/tbib_downloader.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('File Downloader'),
),
body: DownloadPage(),
),
);
}
}
class DownloadPage extends StatefulWidget {
@override
_DownloadPageState createState() => _DownloadPageState();
}
class _DownloadPageState extends State<DownloadPage> {
final Downloader downloader = Downloader();
@override
void initState() {
super.initState();
initDownloader();
}
void initDownloader() async {
await downloader.initialize(
context: context,
requestCode: 1024,
);
}
void startDownload() async {
String url = "https://example.com/file.zip"; // 替换为实际文件URL
String fileName = "file.zip";
String saveDir = await downloader.getDir(type: DownloadPathType.APPLICATION);
DownloadTask task = await downloader.create(
taskId: 1,
url: url,
savedDir: saveDir,
fileName: fileName,
showNotification: true,
openFileFromNotification: true,
);
task.start(
onCompleted: (taskId, filePath) async {
print("Download completed: $filePath");
// 这里可以处理下载完成后的逻辑,比如通知用户或打开文件
},
onError: (taskId, error, statusCode) {
print("Download error: $error, Status Code: $statusCode");
},
onCanceled: (taskId) {
print("Download canceled: $taskId");
},
onProgress: (taskId, progress) {
print("Download progress: $progress");
},
);
}
@override
Widget build(BuildContext context) {
return Center(
child: ElevatedButton(
onPressed: startDownload,
child: Text('Start Download'),
),
);
}
}
6. 处理下载回调
在上述代码中,startDownload
方法负责启动下载任务,并处理各种回调,包括下载完成、错误、取消和进度更新。
注意事项
- 请确保在实际项目中处理各种权限请求和错误处理。
- 根据需求调整文件保存路径和文件名。
tbib_downloader
插件的具体方法和参数可能会随版本更新而变化,请参考最新的官方文档。
这样,你就可以在Flutter应用中使用tbib_downloader
插件进行文件下载了。