Mastering Bluetooth Low Energy (BLE) in Flutter with Flutter Blue Plus

Integrating Bluetooth Low Energy (BLE) into a Flutter app can be challenging—whether it’s dealing with platform-specific quirks, managing background operations, or ensuring seamless communication with multiple devices. But with Flutter Blue Plus, these complexities become manageable, allowing developers to focus on building powerful, cross-platform BLE applications.

In this guide, we’ll explore how Flutter Blue Plus simplifies BLE integration, covering setup, device discovery, connection management, data transfer, and advanced operations like background execution.

What is Flutter Blue Plus?

Flutter Blue Plus is a Flutter plugin designed for BLE Central Role operations, enabling mobile apps to interact with BLE peripherals (like fitness trackers, IoT sensors, and medical devices).

Key Features:

  • ✅ Cross-Platform Support – Works on Android, iOS, macOS, and Windows (Linux support in development).
  • ✅ Simplified API – Easy-to-use methods for scanning, connecting, reading, and writing data.
  • ✅ Background Execution – Keeps BLE operations running even when the app is in the background.
  • ✅ MTU Negotiation – Optimizes data transfer speeds by adjusting packet sizes.
  • ✅ Events API – Monitors device states, connection drops, and real-time updates.

Setting Up Flutter Blue Plus

1. Add the Dependency

Include Flutter Blue Plus and permission_handler in your pubspec.yaml:

dependencies:
  flutter_blue_plus: ^2.0.0  # Latest stable version
  permission_handler: ^10.4.0

Run flutter pub get to install.

2. Configure Platform-Specific Permissions

Android (AndroidManifest.xml)

<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.BLUETOOTH_SCAN" />
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />

iOS (Info.plist)

<key>NSBluetoothAlwaysUsageDescription</key>
<string>Our app uses Bluetooth to connect with devices.</string>
<key>NSBluetoothPeripheralUsageDescription</key>
<string>Our app needs Bluetooth to communicate with devices.</string>
<key>UIBackgroundModes</key>
<array>
    <string>bluetooth-central</string>
</array>

Scanning for BLE Devices

import 'package:flutter_blue_plus/flutter_blue_plus.dart';

void scanDevices() {
  // Start scanning
  FlutterBluePlus.startScan(timeout: Duration(seconds: 5));

  // Listen to scan results
  FlutterBluePlus.scanResults.listen((results) {
    for (ScanResult result in results) {
      print('Found device: ${result.device.name} (RSSI: ${result.rssi})');
    }
  });

  // Stop scanning after timeout
  FlutterBluePlus.stopScan();
}

Connecting to a BLE Device

Future<void> connectToDevice(BluetoothDevice device) async {
  try {
    await device.connect(autoConnect: false, timeout: Duration(seconds: 10));
    print("Connected to ${device.name}");

    // Discover services
    List<BluetoothService> services = await device.discoverServices();
    for (BluetoothService service in services) {
      print("Service UUID: ${service.uuid}");
    }
  } catch (e) {
    print("Connection failed: $e");
  }
}

Reading & Writing Data

Reading from a Characteristic

Future<void> readCharacteristic(BluetoothCharacteristic characteristic) async {
  List<int> value = await characteristic.read();
  print("Read value: $value");
}

Writing to a Characteristic

Future<void> writeCharacteristic(BluetoothCharacteristic characteristic) async {
  await characteristic.write([0x01, 0x02, 0x03]);
  print("Data written successfully");
}

Long Writes (Large Data Transfer)

Future<void> sendLargeData(BluetoothCharacteristic characteristic) async {
  List<int> largeData = List.generate(512, (index) => index % 256);
  await characteristic.write(largeData, allowLongWrite: true);
  print("Large data sent");
}

Managing Background BLE Operations

iOS (Background Mode)

Ensure UIBackgroundModes is set in Info.plist.

Android (Foreground Service)

Use flutter_foreground_task to keep BLE alive:

import 'package:flutter_foreground_task/flutter_foreground_task.dart';

void initBackgroundService() {
  FlutterForegroundTask.init(
    androidNotificationOptions: AndroidNotificationOptions(
      channelId: 'ble_channel',
      channelName: 'BLE Service',
      channelDescription: 'Running BLE in background',
    ),
  );
  FlutterForegroundTask.startService(
    notificationTitle: 'BLE Active',
    notificationText: 'Maintaining connection',
  );
}

Handling Multiple Devices & Connection States

void monitorDeviceStates(BluetoothDevice device) {
  device.state.listen((state) {
    if (state == BluetoothDeviceState.connected) {
      print("${device.name} is connected");
    } else if (state == BluetoothDeviceState.disconnected) {
      print("${device.name} disconnected");
      // Auto-reconnect logic
      device.connect();
    }
  });
}

Conclusion

Flutter Blue Plus is the ultimate solution for integrating BLE into Flutter apps, offering:

  • ✔ Simplified API for scanning, connecting, and data transfer.
  • ✔ Cross-platform support (Android, iOS, macOS, Windows).
  • ✔ Background execution for uninterrupted BLE operations.
  • ✔ Optimized data transfer with MTU negotiation.

Whether you’re building a fitness tracker, IoT app, or medical device integration, Flutter Blue Plus ensures reliable, efficient, and scalable BLE communication.

🚀 Start building smarter Bluetooth apps today with Flutter Blue Plus!

Summary
Mastering Bluetooth Low Energy (BLE) in Flutter with Flutter Blue Plus
Article Name
Mastering Bluetooth Low Energy (BLE) in Flutter with Flutter Blue Plus
Description
Flutter Blue Plus is a Flutter plugin designed for BLE Central Role operations, enabling mobile apps to interact with BLE peripherals.
Author
Publisher Name
raheemdev.com
Publisher Logo

Leave a Comment

Ads Blocker Image Powered by Code Help Pro

Ads Blocker Detected!!!

We have detected that you are using extensions to block ads. Please support us by disabling these ads blocker.

Powered By
100% Free SEO Tools - Tool Kits PRO