Flutter蓝牙共享插件flutter_bluetooth_sharing的使用
Flutter蓝牙共享插件flutter_bluetooth_sharing的使用
一个用于在两台移动设备之间通过蓝牙共享数据的Flutter插件。
特性
- 发现附近的蓝牙设备。
- 开始广播以使其他设备能够发现你。
- 连接到已发现的蓝牙设备并共享数据。
安装
在你的pubspec.yaml
文件中添加以下依赖:
dependencies:
flutter_bluetooth_sharing: ^1.0.0
示例
import 'package:flutter/material.dart';
import 'package:flutter_bluetooth_sharing/flutter_bluetooth_sharing.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
[@override](/user/override)
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('蓝牙共享示例'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
ElevatedButton(
onPressed: _startDiscovery,
child: Text('开始搜索'),
),
ElevatedButton(
onPressed: _startAdvertising,
child: Text('开始广播'),
),
ElevatedButton(
onPressed: _sendData,
child: Text('发送数据'),
),
],
),
),
),
);
}
void _startDiscovery() async {
try {
await FlutterBluetoothSharing.startDiscovery();
print('搜索开始。');
} catch (e) {
print('搜索时发生错误: $e');
}
}
void _startAdvertising() async {
try {
await FlutterBluetoothSharing.startAdvertising();
print('广播开始。');
} catch (e) {
print('广播时发生错误: $e');
}
}
void _sendData() async {
try {
String data = '你好,这是来自设备A的数据!';
await FlutterBluetoothSharing.sendData(data);
print('数据发送成功: $data');
} catch (e) {
print('发送数据时发生错误: $e');
}
}
}
更完整的示例
import 'dart:io';
import 'package:device_info_plus/device_info_plus.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bluetooth_sharing/flutter_bluetooth_sharing.dart';
import 'package:permission_handler/permission_handler.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatefulWidget {
[@override](/user/override)
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
List<BluetoothDevice> discoveredDevices = [];
[@override](/user/override)
void initState() {
WidgetsBinding.instance.addPostFrameCallback((_) {
Future.delayed(Duration(milliseconds: 1000), () async {
await isBTPermissionGiven();
});
});
super.initState();
}
Future<bool> isBTPermissionGiven() async {
if (Platform.isIOS) {
if (!await Permission.bluetooth.isRestricted) {
return true;
} else {
var response = await [Permission.bluetooth].request();
return response[Permission.bluetooth]?.isGranted == true;
}
} else if (Platform.isAndroid) {
var isAndroidS = (int.tryParse(
(await DeviceInfoPlugin().androidInfo).version.release) ?? 0) >=
11;
if (isAndroidS) {
if (await Permission.bluetoothScan.isGranted) {
return true;
} else {
var response = await [
Permission.bluetoothScan,
Permission.bluetoothConnect
].request();
return response[Permission.bluetoothScan]?.isGranted == true &&
response[Permission.bluetoothConnect]?.isGranted == true;
}
} else {
return true;
}
}
return false;
}
void _startDiscovery() async {
try {
await FlutterBluetoothSharing.startDiscovery();
print('搜索开始。');
_discoverDevices();
} catch (e) {
print('搜索时发生错误: $e');
}
}
void _connectToDevice(BluetoothDevice device) async {
try {
print('设备: ${device.toMap()}');
await FlutterBluetoothSharing.connectToDevice(device);
print('连接到设备: ${device.name}');
} catch (e) {
print('连接到设备时发生错误: $e');
}
}
void _sendData() async {
try {
String data = '你好,这是来自设备A的数据!';
await FlutterBluetoothSharing.sendData(data);
print('数据发送成功: $data');
} catch (e) {
print('发送数据时发生错误: $e');
}
}
void _discoverDevices() async {
try {
List<BluetoothDevice> devices = await FlutterBluetoothSharing.getDiscoverableDevices();
setState(() {
discoveredDevices = devices;
});
} catch (e) {
print('发现设备时发生错误: $e');
}
}
[@override](/user/override)
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('蓝牙共享示例'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
ElevatedButton(
onPressed: _startDiscovery,
child: Text('开始搜索'),
),
ElevatedButton(
onPressed: _sendData,
child: Text('发送数据'),
),
SizedBox(height: 20),
Text('已发现设备:'),
Expanded(
child: ListView.builder(
itemCount: discoveredDevices.length,
itemBuilder: (context, index) {
final device = discoveredDevices[index];
return ListTile(
title: Text(device.name),
subtitle: Text(device.address),
onTap: () => _connectToDevice(device),
);
},
),
),
],
),
),
),
);
}
}
更多关于Flutter蓝牙共享插件flutter_bluetooth_sharing的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter蓝牙共享插件flutter_bluetooth_sharing的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
flutter_bluetooth_sharing
是一个用于在 Flutter 应用中实现蓝牙文件共享的插件。使用这个插件,开发者可以轻松地在 Flutter 应用中实现发送和接收文件的功能。以下是如何在 Flutter 项目中使用 flutter_bluetooth_sharing
插件的基本步骤。
1. 添加依赖
首先,你需要在 pubspec.yaml
文件中添加 flutter_bluetooth_sharing
插件的依赖:
dependencies:
flutter:
sdk: flutter
flutter_bluetooth_sharing: ^0.0.1 # 请根据最新版本号进行替换
然后运行 flutter pub get
以安装依赖。
2. 导入插件
在你的 Dart 文件中导入 flutter_bluetooth_sharing
插件:
import 'package:flutter_bluetooth_sharing/flutter_bluetooth_sharing.dart';
3. 初始化蓝牙共享
在使用插件之前,通常需要初始化蓝牙共享功能。你可以通过调用 FlutterBluetoothSharing.init()
来初始化插件:
void initBluetoothSharing() async {
await FlutterBluetoothSharing.init();
}
4. 发送文件
要发送文件,你可以使用 FlutterBluetoothSharing.shareFile
方法。这个方法需要文件的路径作为参数:
void sendFile(String filePath) async {
try {
await FlutterBluetoothSharing.shareFile(filePath);
print('File shared successfully');
} catch (e) {
print('Failed to share file: $e');
}
}
5. 接收文件
接收文件的功能通常依赖于系统级的蓝牙文件传输功能,因此你可能不需要额外的代码来处理接收文件的逻辑。文件接收后,系统会将其保存到设备的下载目录中。
6. 权限处理
在使用蓝牙共享功能时,确保你的应用具有必要的权限。通常需要以下权限:
- BLUETOOTH 和 BLUETOOTH_ADMIN:用于蓝牙连接和管理。
- ACCESS_FINE_LOCATION:用于扫描和连接附近的蓝牙设备。
在 AndroidManifest.xml
中添加以下权限:
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
在 iOS 的 Info.plist
中添加以下键值对:
<key>NSBluetoothAlwaysUsageDescription</key>
<string>We need Bluetooth access to share files</string>
<key>NSBluetoothPeripheralUsageDescription</key>
<string>We need Bluetooth access to share files</string>
7. 请求运行时权限(仅限 Android)
在 Android 6.0 及以上版本中,你需要在运行时请求 ACCESS_FINE_LOCATION
权限。可以使用 permission_handler
插件来实现这一点:
dependencies:
permission_handler: ^10.0.0
然后请求权限:
void requestPermissions() async {
var status = await Permission.locationWhenInUse.status;
if (status.isDenied) {
await Permission.locationWhenInUse.request();
}
}
8. 示例代码
以下是一个简单的示例,展示了如何使用 flutter_bluetooth_sharing
发送文件:
import 'package:flutter/material.dart';
import 'package:flutter_bluetooth_sharing/flutter_bluetooth_sharing.dart';
import 'package:permission_handler/permission_handler.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
[@override](/user/override)
Widget build(BuildContext context) {
return MaterialApp(
home: BluetoothSharingPage(),
);
}
}
class BluetoothSharingPage extends StatefulWidget {
[@override](/user/override)
_BluetoothSharingPageState createState() => _BluetoothSharingPageState();
}
class _BluetoothSharingPageState extends State<BluetoothSharingPage> {
[@override](/user/override)
void initState() {
super.initState();
initBluetoothSharing();
requestPermissions();
}
void initBluetoothSharing() async {
await FlutterBluetoothSharing.init();
}
void requestPermissions() async {
var status = await Permission.locationWhenInUse.status;
if (status.isDenied) {
await Permission.locationWhenInUse.request();
}
}
void sendFile() async {
String filePath = '/path/to/your/file'; // 替换为实际文件路径
try {
await FlutterBluetoothSharing.shareFile(filePath);
print('File shared successfully');
} catch (e) {
print('Failed to share file: $e');
}
}
[@override](/user/override)
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Bluetooth Sharing'),
),
body: Center(
child: ElevatedButton(
onPressed: sendFile,
child: Text('Send File via Bluetooth'),
),
),
);
}
}