flutter_blue 0.4.0

  • README.md
  • CHANGELOG.md
  • Example
  • Installing
  • Versions
  • 95

pub package


FlutterBlue



Introduction

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

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
var scanSubscription = flutterBlue.scan().listen((scanResult) {
    // do something with scan result
});

/// Stop scanning
scanSubscription.cancel();

Connect to a device

/// Create a connection to the device
var deviceConnection = flutterBlue.connect(device).listen((s) {
    if(s == BluetoothDeviceState.connected) {
        // device is connected, do something
    }
});

/// Disconnect from device
deviceConnection.cancel();

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 device.readCharacteristic(c);
    print(value);
}

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

Read and write descriptors

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

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

Set notifications

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

Reference

FlutterBlue API

AndroidiOSDescription
scanStarts a scan for Bluetooth Low Energy devices.
connectEstablishes a connection to the Bluetooth Device.
stateGets the current state of the Bluetooth Adapter.
onStateChangedStream of state changes for the Bluetooth Adapter.

BluetoothDevice API

AndroidiOSDescription
discoverServicesDiscovers services offered by the remote device as well as their characteristics and descriptors.
servicesGets a list of services. Requires that discoverServices() has completed.
readCharacteristicRetrieves the value of a specified characteristic.
readDescriptorRetrieves the value of a specified descriptor.
writeCharacteristicWrites the value of a characteristic.
writeDescriptorWrites the value of a descriptor.
setNotifyValueSets notifications or indications on the specified characteristic.
onValueChangedNotifies when the characteristic's value has changed.
stateGets the current state of the Bluetooth Device.
onStateChangedNotifies of state changes for the Bluetooth Device.

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.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<BluetoothDeviceState>
  • 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.

example/lib/main.dart

// 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 'package:flutter/material.dart';
import 'package:flutter_blue/flutter_blue.dart';
import 'package:flutter_blue_example/widgets.dart';

void main() {
  runApp(new FlutterBlueApp());
}

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

  final String title;

  @override
  _FlutterBlueAppState createState() => new _FlutterBlueAppState();
}

class _FlutterBlueAppState extends State<FlutterBlueApp> {
  FlutterBlue _flutterBlue = FlutterBlue.instance;

  /// Scanning
  StreamSubscription _scanSubscription;
  Map<DeviceIdentifier, ScanResult> scanResults = new Map();
  bool isScanning = false;

  /// State
  StreamSubscription _stateSubscription;
  BluetoothState state = BluetoothState.unknown;

  /// Device
  BluetoothDevice device;
  bool get isConnected => (device != null);
  StreamSubscription deviceConnection;
  StreamSubscription deviceStateSubscription;
  List<BluetoothService> services = new List();
  Map<Guid, StreamSubscription> valueChangedSubscriptions = {};
  BluetoothDeviceState deviceState = BluetoothDeviceState.disconnected;

  @override
  void initState() {
    super.initState();
    // Immediately get the state of FlutterBlue
    _flutterBlue.state.then((s) {
      setState(() {
        state = s;
      });
    });
    // Subscribe to state changes
    _stateSubscription = _flutterBlue.onStateChanged().listen((s) {
      setState(() {
        state = s;
      });
    });
  }

  @override
  void dispose() {
    _stateSubscription?.cancel();
    _stateSubscription = null;
    _scanSubscription?.cancel();
    _scanSubscription = null;
    deviceConnection?.cancel();
    deviceConnection = null;
    super.dispose();
  }

  _startScan() {
    _scanSubscription = _flutterBlue
        .scan(
      timeout: const Duration(seconds: 5),
      /*withServices: [
          new Guid('0000180F-0000-1000-8000-00805F9B34FB')
        ]*/
    )
        .listen((scanResult) {
      print('localName: ${scanResult.advertisementData.localName}');
      print(
          'manufacturerData: ${scanResult.advertisementData.manufacturerData}');
      print('serviceData: ${scanResult.advertisementData.serviceData}');
      setState(() {
        scanResults[scanResult.device.id] = scanResult;
      });
    }, onDone: _stopScan);

    setState(() {
      isScanning = true;
    });
  }

  _stopScan() {
    _scanSubscription?.cancel();
    _scanSubscription = null;
    setState(() {
      isScanning = false;
    });
  }

  _connect(BluetoothDevice d) async {
    device = d;
    // Connect to device
    deviceConnection = _flutterBlue
        .connect(device, timeout: const Duration(seconds: 4))
        .listen(
          null,
          onDone: _disconnect,
        );

    // Update the connection state immediately
    device.state.then((s) {
      setState(() {
        deviceState = s;
      });
    });

    // Subscribe to connection changes
    deviceStateSubscription = device.onStateChanged().listen((s) {
      setState(() {
        deviceState = s;
      });
      if (s == BluetoothDeviceState.connected) {
        device.discoverServices().then((s) {
          setState(() {
            services = s;
          });
        });
      }
    });
  }

  _disconnect() {
    // Remove all value changed listeners
    valueChangedSubscriptions.forEach((uuid, sub) => sub.cancel());
    valueChangedSubscriptions.clear();
    deviceStateSubscription?.cancel();
    deviceStateSubscription = null;
    deviceConnection?.cancel();
    deviceConnection = null;
    setState(() {
      device = null;
    });
  }

  _readCharacteristic(BluetoothCharacteristic c) async {
    await device.readCharacteristic(c);
    setState(() {});
  }

  _writeCharacteristic(BluetoothCharacteristic c) async {
    await device.writeCharacteristic(c, [0x12, 0x34],
        type: CharacteristicWriteType.withResponse);
    setState(() {});
  }

  _readDescriptor(BluetoothDescriptor d) async {
    await device.readDescriptor(d);
    setState(() {});
  }

  _writeDescriptor(BluetoothDescriptor d) async {
    await device.writeDescriptor(d, [0x12, 0x34]);
    setState(() {});
  }

  _setNotification(BluetoothCharacteristic c) async {
    if (c.isNotifying) {
      await device.setNotifyValue(c, false);
      // Cancel subscription
      valueChangedSubscriptions[c.uuid]?.cancel();
      valueChangedSubscriptions.remove(c.uuid);
    } else {
      await device.setNotifyValue(c, true);
      // ignore: cancel_subscriptions
      final sub = device.onValueChanged(c).listen((d) {
        setState(() {
          print('onValueChanged $d');
        });
      });
      // Add to map
      valueChangedSubscriptions[c.uuid] = sub;
    }
    setState(() {});
  }

  _refreshDeviceState(BluetoothDevice d) async {
    var state = await d.state;
    setState(() {
      deviceState = state;
      print('State refreshed: $deviceState');
    });
  }

  _buildScanningButton() {
    if (isConnected || state != BluetoothState.on) {
      return null;
    }
    if (isScanning) {
      return new FloatingActionButton(
        child: new Icon(Icons.stop),
        onPressed: _stopScan,
        backgroundColor: Colors.red,
      );
    } else {
      return new FloatingActionButton(
          child: new Icon(Icons.search), onPressed: _startScan);
    }
  }

  _buildScanResultTiles() {
    return scanResults.values
        .map((r) => ScanResultTile(
              result: r,
              onTap: () => _connect(r.device),
            ))
        .toList();
  }

  List<Widget> _buildServiceTiles() {
    return services
        .map(
          (s) => new ServiceTile(
                service: s,
                characteristicTiles: s.characteristics
                    .map(
                      (c) => new CharacteristicTile(
                            characteristic: c,
                            onReadPressed: () => _readCharacteristic(c),
                            onWritePressed: () => _writeCharacteristic(c),
                            onNotificationPressed: () => _setNotification(c),
                            descriptorTiles: c.descriptors
                                .map(
                                  (d) => new DescriptorTile(
                                        descriptor: d,
                                        onReadPressed: () => _readDescriptor(d),
                                        onWritePressed: () =>
                                            _writeDescriptor(d),
                                      ),
                                )
                                .toList(),
                          ),
                    )
                    .toList(),
              ),
        )
        .toList();
  }

  _buildActionButtons() {
    if (isConnected) {
      return <Widget>[
        new IconButton(
          icon: const Icon(Icons.cancel),
          onPressed: () => _disconnect(),
        )
      ];
    }
  }

  _buildAlertTile() {
    return new Container(
      color: Colors.redAccent,
      child: new ListTile(
        title: new Text(
          'Bluetooth adapter is ${state.toString().substring(15)}',
          style: Theme.of(context).primaryTextTheme.subhead,
        ),
        trailing: new Icon(
          Icons.error,
          color: Theme.of(context).primaryTextTheme.subhead.color,
        ),
      ),
    );
  }

  _buildDeviceStateTile() {
    return new ListTile(
        leading: (deviceState == BluetoothDeviceState.connected)
            ? const Icon(Icons.bluetooth_connected)
            : const Icon(Icons.bluetooth_disabled),
        title: new Text('Device is ${deviceState.toString().split('.')[1]}.'),
        subtitle: new Text('${device.id}'),
        trailing: new IconButton(
          icon: const Icon(Icons.refresh),
          onPressed: () => _refreshDeviceState(device),
          color: Theme.of(context).iconTheme.color.withOpacity(0.5),
        ));
  }

  _buildProgressBarTile() {
    return new LinearProgressIndicator();
  }

  @override
  Widget build(BuildContext context) {
    var tiles = new List<Widget>();
    if (state != BluetoothState.on) {
      tiles.add(_buildAlertTile());
    }
    if (isConnected) {
      tiles.add(_buildDeviceStateTile());
      tiles.addAll(_buildServiceTiles());
    } else {
      tiles.addAll(_buildScanResultTiles());
    }
    return new MaterialApp(
      home: new Scaffold(
        appBar: new AppBar(
          title: const Text('FlutterBlue'),
          actions: _buildActionButtons(),
        ),
        floatingActionButton: _buildScanningButton(),
        body: new Stack(
          children: <Widget>[
            (isScanning) ? _buildProgressBarTile() : new Container(),
            new ListView(
              children: tiles,
            )
          ],
        ),
      ),
    );
  }
}

Use this package as a library

1. Depend on it

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


dependencies:
  flutter_blue: ^0.4.0

2. Install it

You can install packages from the command line:

with Flutter:


$ flutter packages get

Alternatively, your editor might support flutter packages 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';
  
Version Uploaded Documentation Archive
0.4.0 Aug 11, 2018 Go to the documentation of flutter_blue 0.4.0 Download flutter_blue 0.4.0 archive
0.3.3 Apr 3, 2018 Go to the documentation of flutter_blue 0.3.3 Download flutter_blue 0.3.3 archive
0.3.2 Apr 3, 2018 Go to the documentation of flutter_blue 0.3.2 Download flutter_blue 0.3.2 archive
0.3.1 Mar 9, 2018 Go to the documentation of flutter_blue 0.3.1 Download flutter_blue 0.3.1 archive
0.3.0 Mar 7, 2018 Go to the documentation of flutter_blue 0.3.0 Download flutter_blue 0.3.0 archive
0.2.4 Feb 9, 2018 Go to the documentation of flutter_blue 0.2.4 Download flutter_blue 0.2.4 archive
0.2.3 Oct 11, 2017 Go to the documentation of flutter_blue 0.2.3 Download flutter_blue 0.2.3 archive
0.2.2 Sep 6, 2017 Go to the documentation of flutter_blue 0.2.2 Download flutter_blue 0.2.2 archive
0.2.1 Sep 5, 2017 Go to the documentation of flutter_blue 0.2.1 Download flutter_blue 0.2.1 archive
0.2.0 Sep 5, 2017 Go to the documentation of flutter_blue 0.2.0 Download flutter_blue 0.2.0 archive

All 13 versions...

Popularity:
Describes how popular the package is relative to other packages. [more]
92
Health:
Code health derived from static analysis. [more]
96
Maintenance:
Reflects how tidy and up-to-date the package is. [more]
100
Overall:
Weighted score of the above. [more]
95
Learn more about scoring.

We analyzed this package on Aug 11, 2018, and provided a score, details, and suggestions below. Analysis was completed with status completed using:

  • Dart: 2.0.0
  • pana: 0.11.8
  • Flutter: 0.5.7

Platforms

Detected platforms: Flutter

References Flutter, and has no conflicting libraries.

Suggestions

The description is too short.

Add more detail about the package, what it does and what is its target use case. Try to write at least 60 characters.

Package is pre-v1 release.

While there is nothing inherently wrong with versions of 0.*.*, it usually means that the author is still experimenting with the general direction of the API.

Fix lib/gen/flutterblue.pb.dart.

Analysis of lib/gen/flutterblue.pb.dart reported 4 hints:

line 75 col 7: Name types using UpperCamelCase.

line 109 col 7: Name types using UpperCamelCase.

line 111 col 7: Name types using UpperCamelCase.

line 145 col 7: Name types using UpperCamelCase.

Fix lib/gen/flutterblue.pbenum.dart.

Analysis of lib/gen/flutterblue.pbenum.dart reported 4 hints:

line 10 col 7: Name types using UpperCamelCase.

line 38 col 7: Name types using UpperCamelCase.

line 60 col 7: Name types using UpperCamelCase.

line 78 col 7: Name types using UpperCamelCase.

Fix additional 9 files with analysis or formatting issues.

Additional issues in the following files:

  • lib/flutter_blue.dart (Run flutter format to format lib/flutter_blue.dart.)
  • lib/gen/flutterblue.pbjson.dart (Run flutter format to format lib/gen/flutterblue.pbjson.dart.)
  • lib/gen/flutterblue.pbserver.dart (Run flutter format to format lib/gen/flutterblue.pbserver.dart.)
  • lib/src/bluetooth_characteristic.dart (Run flutter format to format lib/src/bluetooth_characteristic.dart.)
  • lib/src/bluetooth_descriptor.dart (Run flutter format to format lib/src/bluetooth_descriptor.dart.)
  • lib/src/bluetooth_device.dart (Run flutter format to format lib/src/bluetooth_device.dart.)
  • lib/src/bluetooth_service.dart (Run flutter format to format lib/src/bluetooth_service.dart.)
  • lib/src/constants.dart (Run flutter format to format lib/src/constants.dart.)
  • lib/src/guid.dart (Run flutter format to format lib/src/guid.dart.)

Dependencies

Package Constraint Resolved Available
Direct dependencies
Dart SDK >=2.0.0-dev.28.0 <3.0.0
convert ^2.0.2 2.0.2
flutter 0.0.0
protobuf ^0.9.1 0.9.1
Transitive dependencies
charcode 1.1.2
collection 1.14.6 1.14.11
fixnum 0.10.7 0.10.8
meta 1.1.5 1.1.6
sky_engine 0.0.99
typed_data 1.1.5 1.1.6
vector_math 2.0.6 2.0.8
Dev dependencies
flutter_test