Flutter蓝牙通信插件flutter_bluetooth_custom的使用

Flutter蓝牙通信插件flutter_bluetooth_custom的使用

Flutter插件flutter_bluetooth_custom允许查找蓝牙设备并发送原始字节数据。它支持Android和iOS平台。

主要功能

  • 支持Android和iOS
  • 扫描蓝牙设备
  • 向设备发送原始List<int> bytes数据

开始使用

对于完整的示例,请查看example文件夹。以下是使用库的关键部分代码示例:

BluetoothManager bluetoothManager = BluetoothManager.instance;
BluetoothDevice _device;

bluetoothManager.startScan(timeout: Duration(seconds: 4));
bluetoothManager.state.listen((state) {
    switch (state) {
    case BluetoothManager.CONNECTED:
        // 处理连接状态
        break;
    case BluetoothManager.DISCONNECTED:
        // 处理断开状态
        break;
    default:
        break;
    }
});
// bluetoothManager.scanResults 是一个发送找到设备的Stream<List<BluetoothDevice>>

// _device = <从 bluetoothManager.scanResults 中获取>

await bluetoothManager.connect(_device);

List<int> bytes = latin1.encode('Hello world!\n').toList();
await bluetoothManager.writeData(bytes);

await bluetoothManager.disconnect();

示例代码

example/lib/main.dart

import 'dart:convert';
// import 'dart:typed_data';

import 'package:flutter/material.dart';
import 'package:flutter_bluetooth_custom/flutter_bluetooth_custom.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Bluetooth scanner',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Bluetooth Scanner'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);
  final String title;

  [@override](/user/override)
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  BluetoothManager bluetoothManager = BluetoothManager.instance;

  bool _connected = false;
  BluetoothDevice _device;
  String tips = 'no device connect';

  [@override](/user/override)
  void initState() {
    super.initState();

    WidgetsBinding.instance.addPostFrameCallback((_) => initBluetooth());
  }

  // 平台消息是异步的,因此我们在异步方法中初始化。
  Future<void> initBluetooth() async {
    bluetoothManager.startScan(timeout: Duration(seconds: 4));

    bool isConnected = await bluetoothManager.isConnected;

    bluetoothManager.state.listen((state) {
      print('当前设备状态: $state');

      switch (state) {
        case BluetoothManager.CONNECTED:
          setState(() {
            _connected = true;
            tips = '连接成功';
          });
          break;
        case BluetoothManager.DISCONNECTED:
          setState(() {
            _connected = false;
            tips = '断开连接';
          });
          break;
        default:
          break;
      }
    });

    if (!mounted) return;

    if (isConnected) {
      setState(() {
        _connected = true;
      });
    }
  }

  void _onConnect() async {
    if (_device != null && _device.address != null) {
      await bluetoothManager.connect(_device);
    } else {
      setState(() {
        tips = '请选择设备';
      });
      print('请选择设备');
    }
  }

  void _onDisconnect() async {
    await bluetoothManager.disconnect();
  }

  void _sendData() async {
    List<int> bytes = latin1.encode('Hello world!\n\n\n').toList();

    // 设置西文字符集。添加导入 'dart:typed_data';
    // List<int> bytes = Uint8List.fromList(List.from('\x1Bt'.codeUnits)..add(6));
    // 包含特殊字符的文本
    // bytes += latin1.encode('blåbærgrød\n\n\n');

    await bluetoothManager.writeData(bytes);
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: RefreshIndicator(
        onRefresh: () => bluetoothManager.startScan(timeout: Duration(seconds: 4)),
        child: SingleChildScrollView(
          child: Column(
            children: [
              Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Padding(
                    padding: EdgeInsets.symmetric(vertical: 10, horizontal: 10),
                    child: Text(tips),
                  ),
                ],
              ),
              Divider(),
              StreamBuilder<List<BluetoothDevice>>(
                stream: bluetoothManager.scanResults,
                initialData: [],
                builder: (c, snapshot) => Column(
                  children: snapshot.data
                      .map((d) => ListTile(
                            title: Text(d.name ?? ''),
                            subtitle: Text(d.address),
                            onTap: () async {
                              setState(() {
                                _device = d;
                              });
                            },
                            trailing: _device != null && _device.address == d.address
                                ? Icon(
                                    Icons.check,
                                    color: Colors.green,
                                  )
                                : null,
                          ))
                      .toList(),
                ),
              ),
              Divider(),
              Container(
                padding: EdgeInsets.fromLTRB(20, 5, 20, 10),
                child: Column(
                  children: [
                    Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        OutlinedButton(
                          child: Text('连接'),
                          onPressed: _connected ? null : _onConnect,
                        ),
                        SizedBox(width: 10.0),
                        OutlinedButton(
                          child: Text('断开连接'),
                          onPressed: _connected ? _onDisconnect : null,
                        ),
                      ],
                    ),
                    OutlinedButton(
                      child: Text('发送测试数据'),
                      onPressed: _connected ? _sendData : null,
                    ),
                  ],
                ),
              )
            ],
          ),
        ),
      ),
      floatingActionButton: StreamBuilder<bool>(
        stream: bluetoothManager.isScanning,
        initialData: false,
        builder: (c, snapshot) {
          if (snapshot.data) {
            return FloatingActionButton(
              child: Icon(Icons.stop),
              onPressed: () => bluetoothManager.stopScan(),
              backgroundColor: Colors.red,
            );
          } else {
            return FloatingActionButton(
                child: Icon(Icons.search),
                onPressed: () =>
                    bluetoothManager.startScan(timeout: Duration(seconds: 4)));
          }
        },
      ),
    );
  }
}

更多关于Flutter蓝牙通信插件flutter_bluetooth_custom的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter蓝牙通信插件flutter_bluetooth_custom的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


flutter_bluetooth_custom 是一个用于在 Flutter 应用中实现蓝牙通信的插件。虽然它可能不是官方提供的插件,但它的使用方式与常见的蓝牙插件(如 flutter_blue)类似。以下是如何使用 flutter_bluetooth_custom 插件的基本步骤:

1. 添加依赖

首先,你需要在 pubspec.yaml 文件中添加 flutter_bluetooth_custom 插件的依赖。

dependencies:
  flutter:
    sdk: flutter
  flutter_bluetooth_custom: ^版本号

然后运行 flutter pub get 来安装依赖。

2. 请求权限

在使用蓝牙功能之前,你需要在 Android 和 iOS 上请求相应的权限。

Android

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>我们需要访问蓝牙以连接设备</string>
<key>NSBluetoothPeripheralUsageDescription</key>
<string>我们需要访问蓝牙以连接设备</string>
<key>NSLocationWhenInUseUsageDescription</key>
<string>我们需要访问位置以扫描蓝牙设备</string>

3. 初始化蓝牙

在你的 Dart 代码中,初始化蓝牙并检查设备是否支持蓝牙。

import 'package:flutter_bluetooth_custom/flutter_bluetooth_custom.dart';

Future<void> initBluetooth() async {
  bool isBluetoothAvailable = await FlutterBluetoothCustom.isAvailable;
  if (!isBluetoothAvailable) {
    print("设备不支持蓝牙");
    return;
  }

  bool isBluetoothEnabled = await FlutterBluetoothCustom.isEnabled;
  if (!isBluetoothEnabled) {
    print("蓝牙未开启");
    // 可以提示用户开启蓝牙
    await FlutterBluetoothCustom.requestEnable();
  }
}

4. 扫描设备

你可以使用 startScan 方法来扫描附近的蓝牙设备。

void startScanning() {
  FlutterBluetoothCustom.startScan(timeout: Duration(seconds: 10)).listen((device) {
    print("发现设备: ${device.name} - ${device.address}");
  }, onDone: () {
    print("扫描完成");
  });
}

5. 连接设备

扫描到设备后,你可以使用 connect 方法来连接设备。

void connectToDevice(String address) async {
  try {
    await FlutterBluetoothCustom.connect(address);
    print("连接成功");
  } catch (e) {
    print("连接失败: $e");
  }
}

6. 发送和接收数据

连接成功后,你可以使用 write 方法发送数据,并通过监听 onDataReceived 来接收数据。

void sendData(String data) async {
  try {
    await FlutterBluetoothCustom.write(data);
    print("数据发送成功");
  } catch (e) {
    print("数据发送失败: $e");
  }
}

void listenForData() {
  FlutterBluetoothCustom.onDataReceived.listen((data) {
    print("收到数据: $data");
  });
}

7. 断开连接

使用 disconnect 方法来断开与设备的连接。

void disconnectDevice() async {
  try {
    await FlutterBluetoothCustom.disconnect();
    print("断开连接成功");
  } catch (e) {
    print("断开连接失败: $e");
  }
}

8. 处理异常和错误

在实际使用中,可能会遇到各种异常和错误,建议在代码中加入适当的错误处理机制。

9. 清理资源

在应用退出或不再需要蓝牙功能时,记得清理资源。

void disposeBluetooth() {
  FlutterBluetoothCustom.stopScan();
  FlutterBluetoothCustom.disconnect();
}
回到顶部