flutter_blue 0.2.3

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

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.

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';

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;
  List<BluetoothService> services = new List();
  StreamSubscription<List<int>> valueChangedSubscription;
  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))
        .listen((scanResult) {
      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
    device.onStateChanged().listen((s) {
      setState(() {
        deviceState = s;
      });
      if (s == BluetoothDeviceState.connected) {
        device.discoverServices().then((s) {
          setState(() {
            services = s;
          });
        });
      }
    });
  }

  _disconnect() {
    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);
    } else {
      await device.setNotifyValue(c, true);
      valueChangedSubscription = device.onValueChanged(c).listen((d) {
        setState(() {
          print('onValueChanged $d');
        });
      });
    }
    setState(() {});
  }

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

  _buildScanningButton(BuildContext context) {
    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(BuildContext context) {
    return scanResults.values
        .map((s) => new ListTile(
              title: new Text(s.device.name),
              subtitle: new Text(s.device.id.toString()),
              leading: new Text(s.rssi.toString()),
              onTap: () => _connect(s.device),
            ))
        .toList();
  }

  _buildDescriptorTile(BuildContext context, BluetoothDescriptor d) {
    var title = new Column(
      mainAxisAlignment: MainAxisAlignment.center,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        const Text('Descriptor'),
        new Text('0x${d.uuid.toString().toUpperCase().substring(4, 8)}',
            style: Theme
                .of(context)
                .textTheme
                .body1
                .copyWith(color: Theme.of(context).textTheme.caption.color))
      ],
    );
    return new ListTile(
      title: new ListTile(
        title: title,
        subtitle: new Text(d.value.toString()),
        trailing: new Row(
          children: <Widget>[
            new IconButton(
              icon: new Icon(
                Icons.file_download,
                color: Theme.of(context).iconTheme.color.withOpacity(0.5),
              ),
              onPressed: () => _readDescriptor(d),
            ),
            new IconButton(
              icon: new Icon(
                Icons.file_upload,
                color: Theme.of(context).iconTheme.color.withOpacity(0.5),
              ),
              onPressed: () => _writeDescriptor(d),
            )
          ],
        ),
      ),
    );
  }

  _buildCharacteristicTile(BuildContext context, BluetoothCharacteristic c) {
    var descriptorTiles =
        c.descriptors.map((d) => _buildDescriptorTile(context, d)).toList();
    var actions = new Row(
      children: <Widget>[
        new IconButton(
          icon: new Icon(
            Icons.file_download,
            color: Theme.of(context).iconTheme.color.withOpacity(0.5),
          ),
          onPressed: () => _readCharacteristic(c),
        ),
        new IconButton(
          icon: new Icon(Icons.file_upload,
              color: Theme.of(context).iconTheme.color.withOpacity(0.5)),
          onPressed: () => _writeCharacteristic(c),
        ),
        new IconButton(
          icon: new Icon(c.isNotifying ? Icons.sync_disabled : Icons.sync,
              color: Theme.of(context).iconTheme.color.withOpacity(0.5)),
          onPressed: () => _setNotification(c),
        )
      ],
    );

    var title = new Column(
      mainAxisAlignment: MainAxisAlignment.center,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        const Text('Characteristic'),
        new Text('0x${c.uuid.toString().toUpperCase().substring(4, 8)}',
            style: Theme
                .of(context)
                .textTheme
                .body1
                .copyWith(color: Theme.of(context).textTheme.caption.color))
      ],
    );

    if (descriptorTiles.length > 0) {
      return new ExpansionTile(
        title: new ListTile(
          title: title,
          subtitle: new Text(c.value.toString()),
          trailing: actions,
        ),
        children: descriptorTiles,
      );
    } else {
      return new ListTile(
        title: title,
        subtitle: new Text(c.value.toString()),
        trailing: actions,
      );
    }
  }

  _buildServiceTile(BuildContext context, BluetoothService s) {
    var characteristicsTiles = s.characteristics
        .map((c) => _buildCharacteristicTile(context, c))
        .toList();
    if (characteristicsTiles.length > 0) {
      return new ExpansionTile(
        title: new Column(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            const Text('Service'),
            new Text('0x${s.uuid.toString().toUpperCase().substring(4, 8)}',
                style: Theme
                    .of(context)
                    .textTheme
                    .body1
                    .copyWith(color: Theme.of(context).textTheme.caption.color))
          ],
        ),
        children: characteristicsTiles,
      );
    } else {
      return new ListTile(
        title: const Text('Service'),
        subtitle:
            new Text('0x${s.uuid.toString().toUpperCase().substring(4, 8)}'),
      );
    }
  }

  _buildServiceTiles(BuildContext context) {
    return services.map((s) => _buildServiceTile(context, s)).toList();
  }

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

  _buildAlertTile(BuildContext context) {
    return new Container(
      color: Colors.redAccent,
      child: new ListTile(
        title: new Text(
          'Bluetooth is not turned on!',
          style: Theme.of(context).primaryTextTheme.subhead,
        ),
        trailing: new Icon(
          Icons.error,
          color: Theme.of(context).primaryTextTheme.subhead.color,
        ),
      ),
    );
  }

  _buildDeviceStateTile(BuildContext context) {
    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(BuildContext context) {
    return new LinearProgressIndicator();
  }

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

2. Install it

You can install packages from the command line:

with pub:


$ pub get

with Flutter:


$ flutter pub get

Alternatively, your editor might support pub get or 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';
  
Version Uploaded Documentation Archive
0.5.0 Feb 4, 2019 Go to the documentation of flutter_blue 0.5.0 Download flutter_blue 0.5.0 archive
0.4.2 Dec 29, 2018 Go to the documentation of flutter_blue 0.4.2 Download flutter_blue 0.4.2 archive
0.4.1 Oct 9, 2018 Go to the documentation of flutter_blue 0.4.1 Download flutter_blue 0.4.1 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

All 16 versions...

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

The package version is not analyzed, because it does not support Dart 2. Until this is resolved, the package will receive a health and maintenance score of 0.

Analysis issues and suggestions

Support Dart 2 in pubspec.yaml.

The SDK constraint in pubspec.yaml doesn't allow the Dart 2.0.0 release. For information about upgrading it to be Dart 2 compatible, please see https://dart.dev/dart-2#migration.

Maintenance issues and suggestions

Make sure dartdoc successfully runs on your package's source files. (-10 points)

Dependencies were not resolved.

Dependencies

Package Constraint Resolved Available
Direct dependencies
Dart SDK >=1.8.0 <2.0.0