← All posts

4 min read

Connecting a Flutter App to an ESP32 over BLE: What Goes Wrong

Flutter and ESP32 over Bluetooth Low Energy with flutter_blue_plus: permissions, device identification, MTU limits, notifications and reconnects.

  • Flutter
  • BLE
  • IoT
  • Native
Cover illustration for Connecting a Flutter App to an ESP32 over BLE

Getting a Flutter app to see a Bluetooth device takes an afternoon. Keeping that connection reliable across real phones takes longer. Range Buddy, one of the apps I’ve shipped, talks to live hardware over BLE with flutter_blue_plus, and most of the lessons below came from the gap between “it connected” and “it stays connected”.

The examples use an ESP32 because it’s the board most hardware projects start on, but the app side applies to any BLE peripheral.

Agree on the protocol first

Before writing Dart or firmware, write down the contract between them:

  • Service and characteristic UUIDs
  • Which characteristics are read, write and notify
  • Byte layout, endianness and units for every field
  • How messages longer than one packet are split
  • What each error looks like
  • A protocol version field, because firmware and apps update at different times

A one-page document here saves a lot of arguing about which side is broken.

On the ESP32, one classic mistake is forgetting that advertising stops once a client connects. If the firmware doesn’t restart advertising on disconnect, the app can never reconnect until the device reboots.

class ServerCallbacks : public BLEServerCallbacks {
  void onDisconnect(BLEServer* server) override {
    BLEDevice::startAdvertising();
  }
};

Permissions differ by OS version

Android 12 and later use BLUETOOTH_SCAN and BLUETOOTH_CONNECT. Older versions need location permission to scan.

<uses-permission android:name="android.permission.BLUETOOTH_SCAN"
    android:usesPermissionFlags="neverForLocation" />
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
<uses-permission android:name="android.permission.BLUETOOTH" android:maxSdkVersion="30" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" android:maxSdkVersion="30" />

Only use neverForLocation if you really don’t derive location from scan results. iOS needs NSBluetoothAlwaysUsageDescription in Info.plist, and App Review will read the wording, so explain what the Bluetooth connection is for.

Also handle Bluetooth being switched off. Your scan will fail quietly otherwise.

Scan by service, and don’t rely on the MAC address

Filter scans by your service UUID so you aren’t sorting through every nearby speaker and watch.

await FlutterBluePlus.adapterState
    .where((s) => s == BluetoothAdapterState.on)
    .first;

await FlutterBluePlus.startScan(
  withServices: [Guid(serviceUuid)],
  timeout: const Duration(seconds: 10),
);

iOS doesn’t expose the MAC address. It gives you an identifier that’s generated per phone. So if you need to recognise a specific device across phones, put a serial number in the advertising data or a readable characteristic.

Connect, then wait for the right order

The order matters: connect, negotiate MTU, discover services, then enable notifications.

await device.connect(); // Recent package versions may need extra arguments: check your version.
if (Platform.isAndroid) {
  await device.requestMtu(247);
}
final services = await device.discoverServices();

flutter_blue_plus changed its API and licensing during the 2.x releases, so read the changelog and licence for the version you install. Commercial products may need a paid licence, and that’s better discovered during planning than just before launch.

Twenty bytes is the default

BLE’s default MTU leaves 20 bytes per write. Android can negotiate more with requestMtu. iOS negotiates by itself, so you read the result and can’t ask for a value. Never assume a size. Use what was negotiated, and split larger payloads:

final chunkSize = device.mtuNow - 3;
for (var i = 0; i < data.length; i += chunkSize) {
  final end = min(i + chunkSize, data.length);
  await characteristic.write(data.sublist(i, end), withoutResponse: false);
}

For anything important, add a sequence number and a checksum. Writes without response are faster, but there’s no confirmation they arrived, so that’s a poor fit for firmware updates or commands that matter.

Notifications and stale listeners

Enable notifications, keep the subscription, and cancel it when the device disconnects.

await characteristic.setNotifyValue(true);
final sub = characteristic.onValueReceived.listen(_handlePacket);
device.cancelWhenDisconnected(sub);

A notification doesn’t line up with one logical message. If the device sends a 200-byte reading in parts, your code has to buffer and reassemble it. Parsing should live in plain Dart classes that you can unit test without any hardware.

Treat disconnection as normal

People walk away, phones lock, batteries die. Design the connection as a state machine (scanning, connecting, ready, reconnecting, failed) and show that state to the user.

Android has a well-known catch-all failure, GATT error 133. When it appears, disconnect fully, wait briefly and retry with a limit, rather than hammering the connection. Some phones behave noticeably worse than others, so test on several brands. The emulator won’t help you, since BLE needs real hardware.

Background behaviour

iOS needs the bluetooth-central background mode, and even then it restricts what you can do. Android may need a foreground service for long-running connections. Read what iOS and Android actually allow in the background before promising a client that the app will “always stay connected”.

Testing without losing your mind

  • Keep a generic BLE app like nRF Connect on hand to separate firmware faults from app faults
  • Build a fake device class behind an interface so UI work doesn’t need hardware
  • Log raw bytes in debug builds
  • Test: out of range, Bluetooth toggled off, firmware rebooted mid-transfer, two phones competing for one device

Takeaways

  • Write the byte-level protocol before the code.
  • Restart advertising on the ESP32 after a disconnect.
  • Don’t identify devices by MAC address on iOS.
  • Use the negotiated MTU and handle message reassembly.
  • Check the licence on your BLE package.
  • Treat reconnecting as a main feature.

If you’re building hardware and need the app side done properly, get in touch with what your device does and how it talks.

Comments

Questions, corrections or your own experience — leave a comment below (GitHub sign-in).