flutter_blue 0.7.0

  • Readme
  • Changelog
  • Example
  • Installing
  • 98

pub package Chat


Introduction #

FlutterBlue is a bluetooth plugin for Flutter, a new mobile SDK to help developers build modern apps for iOS and Android.

Alpha version #

This library is actively developed alongside production apps, and the API will evolve as we continue our way to version 1.0.

Please be fully prepared to deal with breaking changes.

Having trouble adapting to the latest API? I'd love to hear your use-case, please contact me.

Cross-Platform Bluetooth LE #

FlutterBlue aims to offer the most from both platforms (iOS and Android).

Using the FlutterBlue instance, you can scan for and connect to nearby devices (BluetoothDevice). Once connected to a device, the BluetoothDevice object can discover services (BluetoothService), characteristics (BluetoothCharacteristic), and descriptors (BluetoothDescriptor). The BluetoothDevice object is then used to directly interact with characteristics and descriptors.

Usage #

Obtain an instance #

FlutterBlue flutterBlue = FlutterBlue.instance;

Scan for devices #

// Start scanning
flutterBlue.startScan(timeout: Duration(seconds: 4));

// Listen to scan results
var subscription = flutterBlue.scanResults.listen((results) {
    // do something with scan results
    for (ScanResult r in results) {
        print('${r.device.name} found! rssi: ${r.rssi}');

// Stop scanning

Connect to a device #

// Connect to the device
await device.connect();

// Disconnect from device

Discover services #

List<BluetoothService> services = await device.discoverServices();
services.forEach((service) {
    // do something with service

Read and write characteristics #

// Reads all characteristics
var characteristics = service.characteristics;
for(BluetoothCharacteristic c in characteristics) {
    List<int> value = await c.read();

// Writes to a characteristic
await c.write([0x12, 0x34])

Read and write descriptors #

// Reads all descriptors
var descriptors = characteristic.descriptors;
for(BluetoothDescriptor d in descriptors) {
    List<int> value = await d.read();

// Writes to a descriptor
await d.write([0x12, 0x34])

Set notifications and listen to changes #

await characteristic.setNotifyValue(true);
characteristic.value.listen((value) {
    // do something with new value

Read the MTU and request larger size #

final mtu = await device.mtu.first;
await device.requestMtu(512);

Note that iOS will not allow that you request the MTU size, but will always try to negotiate the highest possible MTU (iOS supports up to MTU size 185)

Reference #

FlutterBlue API #

scanStarts a scan for Bluetooth Low Energy devices.
stateStream of state changes for the Bluetooth Adapter.
isAvailableChecks whether the device supports Bluetooth.
isOnChecks if Bluetooth functionality is turned on.

BluetoothDevice API #

connectEstablishes a connection to the device.
disconnectCancels an active or pending connection to the device.
discoverServicesDiscovers services offered by the remote device as well as their characteristics and descriptors.
servicesGets a list of services. Requires that discoverServices() has completed.
stateStream of state changes for the Bluetooth Device.
mtuStream of mtu size changes.
requestMtuRequest to change the MTU for the device.

BluetoothCharacteristic API #

readRetrieves the value of the characteristic.
writeWrites the value of the characteristic.
setNotifyValueSets notifications or indications on the characteristic.
valueStream of characteristic's value when changed.

BluetoothDescriptor API #

readRetrieves the value of the descriptor.
writeWrites the value of the descriptor.

Troubleshooting #

Scanning for service UUID's doesn't return any results #

Make sure the device is advertising which service UUID's it supports. This is found in the advertisement packet as UUID 16 bit complete list or UUID 128 bit complete list.

0.7.0 #

  • Support v2 android embedding.
  • Various bug and documentation fixes.

0.6.3+1 #

  • Fix compilation issue with iOS.
  • Bump protobuf version to 1.0.0.

0.6.3 #

  • Update project files for Android and iOS.
  • Remove dependency on protoc for iOS.

0.6.2 #

  • Add mtu and requestMtu to BluetoothDevice.

0.6.0+4 #

  • Fix duplicate characteristic notifications when connection lost.
  • Fix duplicate characteristic notifications when reconnecting.
  • Add minimum SDK version of 18 for the plugin.
  • Documentation updates.

0.6.0 #

  • Breaking change. API refactoring with RxDart (see example).
  • Log a more detailed warning at build time about the previous AndroidX migration.
  • Ensure that all channel calls to the Dart side from the Java side are done on the UI thread. This change allows Transactions to work with upcoming Engine restrictions, which require channel calls be made on the UI thread. Note this is an Android only change, the iOS implementation was not impacted.

0.5.0 #

  • Breaking change. Migrate from the deprecated original Android Support Library to AndroidX. This shouldn't result in any functional changes, but it requires any Android apps using this plugin to also migrate if they're using the original support library.

0.4.2+1 #

  • Upgrade Android Gradle plugin to 3.3.0.
  • Refresh iOS build files.

0.4.2 #

  • Set the verbosity of log messages with setLogLevel.
  • Updated iOS and Android project files.
  • autoConnect now configurable for Android.
  • Various bug fixes.

0.4.1 #

  • Fixed bug where setNotifyValue wasn't properly awaitable.
  • Various UI bug fixes to example app.
  • Removed unnecessary intl dependencies in example app.

0.4.0 #

  • Breaking change. Manufacturer Data is now a Map of manufacturer ID's.
  • Service UUID's, service data, tx power level packets fixed in advertising data.
  • Example app updated to show advertising data.
  • Various other bug fixes.

0.3.4 #

  • Updated to use the latest protobuf (^0.9.0+1).
  • Updated other dependencies.

0.3.3 #

  • scan withServices to filter by service UUID's (iOS).
  • Error handled when trying to scan with adapter off (Android).

0.3.2 #

  • Runtime permissions for Android.
  • scan withServices to filter by service UUID's (Android).
  • Scan mode can be specified (Android).
  • Now targets the latest android SDK.
  • Dart 2 compatibility.

0.3.1 #

  • Now allows simultaneous notifications of characteristics.
  • Fixed bug on iOS that was returning discoverServices too early.

0.3.0 #

  • iOS support added.
  • Bug fixed in example causing discoverServices to be called multiple times.
  • Various other bug fixes.

0.2.4 #

  • Breaking change. Upgraded to Gradle 4.1 and Android Studio Gradle plugin 3.0.1. Older Flutter projects need to upgrade their Gradle setup as well in order to use this version of the plugin. Instructions can be found here.

0.2.3 #

  • Bug fixes

0.2.2 #

  • Breaking changes:
  • startScan renamed to scan.
  • ScanResult now returns a BluetoothDevice.
  • connect now takes a BluetoothDevice and returns Stream
  • Added parameter timeout to connect.
  • Automatic disconnect on deviceConnection.cancel().

0.2.1 #

  • Breaking change. Removed stopScan from API, use scanSubscription.cancel() instead.
  • Automatically stops scan when startScan subscription is canceled (thanks to @brianegan).
  • Added timeout parameter to startScan.
  • Updated example app to show new scan functionality.

0.2.0 #

  • Added state and onStateChanged for BluetoothDevice.
  • Updated example to show new functionality.

0.1.1 #

  • Fixed image for pub.dartlang.org.

0.1.0 #

  • Characteristic notifications/indications.
  • Merged in Guid library, removed from pubspec.yaml.

0.0.1 - September 1st, 2017 #

  • Initial Release.


// Copyright 2017, Paul DeMarco.
// All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

import 'dart:async';
import 'dart:math';

import 'package:flutter/material.dart';
import 'package:flutter_blue/flutter_blue.dart';
import 'package:flutter_blue_example/widgets.dart';

void main() {

class FlutterBlueApp extends StatelessWidget {
  Widget build(BuildContext context) {
    return MaterialApp(
      color: Colors.lightBlue,
      home: StreamBuilder<BluetoothState>(
          stream: FlutterBlue.instance.state,
          initialData: BluetoothState.unknown,
          builder: (c, snapshot) {
            final state = snapshot.data;
            if (state == BluetoothState.on) {
              return FindDevicesScreen();
            return BluetoothOffScreen(state: state);

class BluetoothOffScreen extends StatelessWidget {
  const BluetoothOffScreen({Key key, this.state}) : super(key: key);

  final BluetoothState state;

  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.lightBlue,
      body: Center(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: <Widget>[
              size: 200.0,
              color: Colors.white54,
              'Bluetooth Adapter is ${state.toString().substring(15)}.',
              style: Theme.of(context)
                  .copyWith(color: Colors.white),

class FindDevicesScreen extends StatelessWidget {
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Find Devices'),
      body: RefreshIndicator(
        onRefresh: () =>
            FlutterBlue.instance.startScan(timeout: Duration(seconds: 4)),
        child: SingleChildScrollView(
          child: Column(
            children: <Widget>[
                stream: Stream.periodic(Duration(seconds: 2))
                    .asyncMap((_) => FlutterBlue.instance.connectedDevices),
                initialData: [],
                builder: (c, snapshot) => Column(
                  children: snapshot.data
                      .map((d) => ListTile(
                            title: Text(d.name),
                            subtitle: Text(d.id.toString()),
                            trailing: StreamBuilder<BluetoothDeviceState>(
                              stream: d.state,
                              initialData: BluetoothDeviceState.disconnected,
                              builder: (c, snapshot) {
                                if (snapshot.data ==
                                    BluetoothDeviceState.connected) {
                                  return RaisedButton(
                                    child: Text('OPEN'),
                                    onPressed: () => Navigator.of(context).push(
                                            builder: (context) =>
                                                DeviceScreen(device: d))),
                                return Text(snapshot.data.toString());
                stream: FlutterBlue.instance.scanResults,
                initialData: [],
                builder: (c, snapshot) => Column(
                  children: snapshot.data
                        (r) => ScanResultTile(
                          result: r,
                          onTap: () => Navigator.of(context)
                              .push(MaterialPageRoute(builder: (context) {
                            return DeviceScreen(device: r.device);
      floatingActionButton: StreamBuilder<bool>(
        stream: FlutterBlue.instance.isScanning,
        initialData: false,
        builder: (c, snapshot) {
          if (snapshot.data) {
            return FloatingActionButton(
              child: Icon(Icons.stop),
              onPressed: () => FlutterBlue.instance.stopScan(),
              backgroundColor: Colors.red,
          } else {
            return FloatingActionButton(
                child: Icon(Icons.search),
                onPressed: () => FlutterBlue.instance
                    .startScan(timeout: Duration(seconds: 4)));

class DeviceScreen extends StatelessWidget {
  const DeviceScreen({Key key, this.device}) : super(key: key);

  final BluetoothDevice device;

  List<int> _getRandomBytes() {
    final math = Random();
    return [

  List<Widget> _buildServiceTiles(List<BluetoothService> services) {
    return services
          (s) => ServiceTile(
            service: s,
            characteristicTiles: s.characteristics
                  (c) => CharacteristicTile(
                    characteristic: c,
                    onReadPressed: () => c.read(),
                    onWritePressed: () => c.write(_getRandomBytes()),
                    onNotificationPressed: () =>
                    descriptorTiles: c.descriptors
                          (d) => DescriptorTile(
                            descriptor: d,
                            onReadPressed: () => d.read(),
                            onWritePressed: () => d.write(_getRandomBytes()),

  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(device.name),
        actions: <Widget>[
            stream: device.state,
            initialData: BluetoothDeviceState.connecting,
            builder: (c, snapshot) {
              VoidCallback onPressed;
              String text;
              switch (snapshot.data) {
                case BluetoothDeviceState.connected:
                  onPressed = () => device.disconnect();
                  text = 'DISCONNECT';
                case BluetoothDeviceState.disconnected:
                  onPressed = () => device.connect();
                  text = 'CONNECT';
                  onPressed = null;
                  text = snapshot.data.toString().substring(21).toUpperCase();
              return FlatButton(
                  onPressed: onPressed,
                  child: Text(
                    style: Theme.of(context)
                        .copyWith(color: Colors.white),
      body: SingleChildScrollView(
        child: Column(
          children: <Widget>[
              stream: device.state,
              initialData: BluetoothDeviceState.connecting,
              builder: (c, snapshot) => ListTile(
                leading: (snapshot.data == BluetoothDeviceState.connected)
                    ? Icon(Icons.bluetooth_connected)
                    : Icon(Icons.bluetooth_disabled),
                title: Text(
                    'Device is ${snapshot.data.toString().split('.')[1]}.'),
                subtitle: Text('${device.id}'),
                trailing: StreamBuilder<bool>(
                  stream: device.isDiscoveringServices,
                  initialData: false,
                  builder: (c, snapshot) => IndexedStack(
                    index: snapshot.data ? 1 : 0,
                    children: <Widget>[
                        icon: Icon(Icons.refresh),
                        onPressed: () => device.discoverServices(),
                        icon: SizedBox(
                          child: CircularProgressIndicator(
                            valueColor: AlwaysStoppedAnimation(Colors.grey),
                          width: 18.0,
                          height: 18.0,
                        onPressed: null,
              stream: device.mtu,
              initialData: 0,
              builder: (c, snapshot) => ListTile(
                title: Text('MTU Size'),
                subtitle: Text('${snapshot.data} bytes'),
                trailing: IconButton(
                  icon: Icon(Icons.edit),
                  onPressed: () => device.requestMtu(223),
              stream: device.services,
              initialData: [],
              builder: (c, snapshot) {
                return Column(
                  children: _buildServiceTiles(snapshot.data),

Use this package as a library

1. Depend on it

Add this to your package's pubspec.yaml file:

  flutter_blue: ^0.7.0

2. Install it

You can install packages from the command line:

with Flutter:

$ flutter pub get

Alternatively, your editor might support flutter pub get. Check the docs for your editor to learn more.

3. Import it

Now in your Dart code, you can use:

import 'package:flutter_blue/flutter_blue.dart';
Describes how popular the package is relative to other packages. [more]
Code health derived from static analysis. [more]
Reflects how tidy and up-to-date the package is. [more]
Weighted score of the above. [more]
Learn more about scoring.

We analyzed this package on Apr 3, 2020, and provided a score, details, and suggestions below. Analysis was completed with status completed using:

  • Dart: 2.7.1
  • pana: 0.13.6
  • Flutter: 1.12.13+hotfix.8


Package Constraint Resolved Available
Direct dependencies
Dart SDK >=2.0.0-dev.28.0 <3.0.0
convert ^2.1.1 2.1.1
flutter 0.0.0
protobuf ^1.0.0 1.0.1
rxdart ^0.23.1 0.23.1 0.24.0-dev.1
Transitive dependencies
charcode 1.1.3
collection 1.14.11 1.14.12
fixnum 0.10.11
meta 1.1.8
sky_engine 0.0.99
typed_data 1.1.6
vector_math 2.0.8
Dev dependencies
e2e ^0.2.1