【Flutter】flutter_blue_plusの使い方

Flutter

FlutterBluePlusは、Flutter向けのBluetooth Low Energy(BLE)プラグインです。BLEデバイスとの通信や接続を可能にします。以下は、このプラグインの基本的な使用方法やトラブルシューティングに関する情報です。

追記(2024/4/3)

この記事は基本的なflutter_blue_plusのreadme.mdを参考にしています。
が、私はStreamをRiverpodを使って実装することを前提に考えています
このまま書いても動きますが、できればMVVMで上手に管理してください。

また、更新が恐ろしく速いので、エンジニアの皆さん、がんばれ。
たまにバグが増える謎アプデがあります。

概要

FlutterBluePlusは、Flutterで動作するBLE Central Roleプラグインです。
iOS、macOS、Androidのすべてのプラットフォームをサポートしています。

ただし、Bluetooth Classicはサポートされていません。

flutter_blue_plus | Flutter package
Flutter plugin for connecting and communicating with Bluetooth Low Energy devices.

インストール

flutter_blue_plus install | Flutter package
Flutter plugin for connecting and communicating with Bluetooth Low Energy devices.

使用方法

Bluetoothがサポートされているか確認

if (await FlutterBluePlus.isSupported == false) {
    print("Bluetooth not supported by this device");
    return;
}

Bluetoothの状態を監視

FlutterBluePlus.adapterState.listen((BluetoothAdapterState state) {
    print(state);
    if (state == BluetoothAdapterState.on) {
        // Bluetoothがオンになった時の処理
    } else {
        // Bluetoothがオフになった時の処理
    }
});

Bluetoothのオンとオフ(Androidのみ)

if (Platform.isAndroid) {
    await FlutterBluePlus.turnOn();
}

デバイスのスキャン

// スキャン結果のリスナーをセットアップ
var subscription = FlutterBluePlus.scanResults.listen((results) {
    if (results.isNotEmpty) {
        ScanResult r = results.last; // 最後に見つかったデバイス
        print('${r.device.remoteId}: "${r.advertisementData.advName}" found!');
    }
},
onError: (e) => print(e));

// Bluetoothが有効でパーミッションが許可されるまで待機
await FlutterBluePlus.adapterState
    .where((val) => val == BluetoothAdapterState.on)
    .first;

// スキャン開始
await FlutterBluePlus.startScan();

// スキャン停止
await FlutterBluePlus.stopScan();

// リスナーのキャンセル
subscription.cancel();

デバイスへの接続

// 切断時のリスナーを設定
device.connectionState.listen((BluetoothConnectionState state) async {
    if (state == BluetoothConnectionState.disconnected) {
        // デバイスが切断された時の処理
        print("${device.disconnectReasonCode} ${device.disconnectReasonDescription}");
    }
});

// デバイスへの接続
await device.connect();

// デバイスから切断
await device.disconnect();

これは、FlutterBluePlusの基本的な使用例です。詳細な情報や他の機能については、公式のドキュメントやGitHubリポジトリを参照してください。

使用感

更新が早すぎるので、githubを見てください。

GitHub - chipweinberger/flutter_blue_plus: Flutter plugin for connecting and communicationg with Bluetooth Low Energy devices, on Android, iOS, macOS, Web, Linux, Windows.
Flutter plugin for connecting and communicationg with Bluetooth Low Energy devices, on Android, iOS, macOS, Web, Linux, ...
タイトルとURLをコピーしました