FlutterBleLib - A library for all your Bluetooth Low Energy needs in Flutter.

Overview

Frontside Build Status pub package

Flutter BLE library logo

FlutterBleLib

A library for all your Bluetooth Low Energy needs in Flutter. Internally utilises Polidea's MultiPlatformBleAdapter, which runs on RxAndroidBle and RxBluetoothKit.

BLE Simulator

This library supports BLEmulator, the BLE simulator. The simulation allows one to develop without physical smartphone or BLE peripheral and use one's production BLE–related code in automated testing.

Installation

To use this plugin, add flutter_ble_lib as a dependency in your pubspec.yaml file.

Android

Set minSDKVersion in [project]/android/app/build.gradle file to 18.

defaultConfig {
  ...
  minSdkVersion 18
  ...
}

Support for Bluetooth Low Energy has been added in API 18, hence the library requires minSDKVersion to be set to 18. If BLE is not core to your application, you can override it and handle support detection in your code.

Notice: You don't need to add any permissions related to BLE to the AndroidManifest.xml, because they are already declared in the library's native module. However, you still need to request ACCESS_FINE_LOCATION permission at runtime to be able to scan for peripheral. See example's code and example's pubspec.

iOS

Go to [project]/ios directory and run pod install.

Add Privacy - Bluetooth Always Usage Description key to [project]/ios/Runner/Info.plist file.

...
<key>NSBluetoothAlwaysUsageDescriptionkey>
<string>Your own description of the purpose.string>
...

Background mode

To support background capabilities add The bluetooth-central Background Execution Mode key to [project]/ios/Runner/Info.plist file.

...
<key>UIBackgroundModeskey>
<array>
  <string>bluetooth-centralstring>
array>
...

Usage

The library is organised around a few base entities, which are:

  • BleManager
  • Peripheral
  • Service
  • Characteristic
  • Descriptor

You have to create an instance BleManager and initialise underlying native resources. Using that instance you then obtain an instance of Peripheral, which can be used to run operations on the corresponding peripheral.

All operations passing the Dart-native bridge are asynchronous, hence all operations in the plugin return either Future or Stream.

For more informations, see REFERENCE.

Notice: this library will not handle any permissions for you. To be able to scan for peripherals on Android you need ACCESS_FINE_LOCATION according to Android Developer Guide.

Initialising

BleManager bleManager = BleManager();
await bleManager.createClient(); //ready to go!
// your peripheral logic
bleManager.destroyClient(); //remember to release native resources when you're done!

Following snippets assume the library has been initialised.

Handling Bluetooth adapter state

enum BluetoothState {
  UNKNOWN,
  UNSUPPORTED,
  UNAUTHORIZED,
  POWERED_ON,
  POWERED_OFF,
  RESETTING,
}


bleManager.enableRadio(); //ANDROID-ONLY turns on BT. NOTE: doesn't check permissions
bleManager.disableRadio() //ANDROID-ONLY turns off BT. NOTE: doesn't check permissions
BluetoothState currentState = await bleManager.bluetoothState();
bleManager.observeBluetoothState().listen((btState) {
  print(btState);
  //do your BT logic, open different screen, etc.
});

Scanning for peripherals

bleManager.startPeripheralScan(
  uuids: [
    "F000AA00-0451-4000-B000-000000000000",
  ],
).listen((scanResult) {
  //Scan one peripheral and stop scanning
  print("Scanned Peripheral ${scanResult.peripheral.name}, RSSI ${scanResult.rssi}");
  bleManager.stopPeripheralScan();
});

The snippet above starts peripheral scan and stops it after receiving first result. It filters the scan results to those that advertise a service with specified UUID.

NOTE: isConnectable and overflowServiceUuids fields of ScanResult are iOS-only and remain null on Android.

Connecting to saved peripheral

You can try to connect to a peripheral with known ID, be it previously scanned UUID on iOS or a MAC address on Android, and avoid the whole scanning operation in your application. To do so, you need to create an instance of Peripheral using:

< known id >"); ">
Peripheral myPeripheral = bleManager.createUnsafePeripheral("< known id >");

Once you have the instance of the peripheral, you may proceed with the connection. But keep in mind that Android may still not find the peripheral without scanning it first.

Connecting to peripheral

First you must obtain a ScanResult from BleManager.startPeripheralScan().

Peripheral peripheral = scanResult.peripheral;
peripheral.observeConnectionState(emitCurrentValue: true, completeOnDisconnect: true)
  .listen((connectionState) {
    print("Peripheral ${scanResult.peripheral.identifier} connection state is $connectionState");
  });
await peripheral.connect();
bool connected = await peripheral.isConnected();
await peripheral.disconnectOrCancelConnection();

The snippet above starts observing the state of the connection to the peripheral, connects to it, checks if it's connected and then disconnects from it.

Transactions

Methods that do not have counterpart with opposite effect and are asynchronous accept String transactionId as an optional argument, to allow the user to cancel such an operation. The Future returned to Dart will then finish with a BleError(BleErrorCode.operationCancelled...), but this will only discard the result of the operation, the operation itself will be executed either way.

For example, if I decided that I no longer want to run discovery on the selected peripheral:

//assuming peripheral is connected
peripheral.discoverAllServicesAndCharacteristics(transactionId: "discovery");
//will return operation cancelled error after calling the below
bleManager.cancelTransaction("discovery");

Each new operation with the same transactionId will cause the previous one to be cancelled with error, if it hasn't finished yet. If transactionId is set to null or it isn't specified at all, the library sets unique integer transactionId to such operation.

NOTE: Do not to set integers as transactionId as they are used by the library.

Obtaining characteristics

To be able to operate on the peripheral, discovery of its services and characteristics must be run first.

characteristics2 = await services.firstWhere( (service) => service.uuid == "F000AA00-0451-4000-B000-000000000000").characteristics(); //characteristics1 and characteristics2 have the same contents ">
//assuming peripheral is connected
await peripheral.discoverAllServicesAndCharacteristics();
List<Service> services = await peripheral.services(); //getting all services
List<Characteristic> characteristics1 = await peripheral.characteristics("F000AA00-0451-4000-B000-000000000000");
List<Characteristic> characteristics2 = await services.firstWhere(
  (service) => service.uuid == "F000AA00-0451-4000-B000-000000000000").characteristics();

//characteristics1 and characteristics2 have the same contents

Objects representing characteristics have a unique identifer, so they point to one specific characteristic, even if there are multiple service/characteristic uuid matches.

Manipulating characteristics

Below are 3 methods of writing to a characteristic, which all result in the same effect given there's only one service with specified UUID and only one characteristic with specified UUID.

peripheral.writeCharacteristic(
  "F000AA00-0451-4000-B000-000000000000",
  "F000AA02-0451-4000-B000-000000000000",
  Uint8List.fromList([0]),
  false); //returns Characteristic to chain operations more easily

service.writeCharacteristic(
  "F000AA02-0451-4000-B000-000000000000",
  Uint8List.fromList([0]),
  false); //returns Characteristic to chain operations more easily

characteristic.write(Uint8List.fromList([0]), false); //returns void

Monitoring or reading a characteristic from Peripheral/Service level return CharacteristicWithValue object, which is Characteristic with additional Uint8List value property.

Descriptor operations

List of descriptors from a single characteristic can be obtained in a similar fashion to a list of characteristics from a single service, either from Peripheral, Service or Characteristic object. Descriptors can be read/written from Peripheral, Service or Characteristic by supplying necessary UUIDs, or from Descriptor object.

Note: to enable monitoring of characteristic you should use characteristic.monitor() or (peripheral/service).monitorCharacteristic() instead of changing the value of the underlying descriptor yourself.

Facilitated by Frontside

Frontside provided architectural advice and financial support for this library on behalf of Resideo.

Maintained by

This library is maintained by Polidea

Contact us

Learn more about Polidea's BLE services.

Maintainers

TBD

License

Copyright 2019 Polidea Sp. z o.o

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

More from Polidea

Check out other Polidea's BLE libraries:

You might also like...

A Flutter plugin for turning your device into a beacon.

Beacon Broadcast plugin for Flutter A Flutter plugin for turning your device into a beacon. Usage To use this plugin, add beacon_broadcast as a depend

Dec 14, 2022

Flutter beacons plugin for Android and iOS.

Beacons Flutter plugin to work with beacons. Supports Android API 16+ and iOS 8+. Features: Automatic permission management Ranging Monitoring (includ

Jan 6, 2023

Flutter NFC reader plugin for iOS and Android

Flutter NFC reader plugin for iOS and Android

Flutter NFC Reader & Writer A new flutter plugin to help developers looking to use internal hardware inside iOS or Android devices for reading and wri

Dec 30, 2022

Flutter plugin for accessing the NFC features on Android and iOS.

nfc_manager Flutter plugin for accessing the NFC features on Android and iOS. Note: This plugin depends on NFCTagReaderSession (requires iOS 13.0 or l

Jan 1, 2023

Ready for Building Production-Ready Healthcare/ Doctor Consult Android and iOS app UI using Flutter.

Ready for Building Production-Ready Healthcare/ Doctor Consult Android and iOS app UI using Flutter.

Production-Ready Doctor Consultant App - Flutter UI Watch it on YouTube Packages we are using: flutter_svg: link Complete Source code (Patreon) In thi

Jan 1, 2023

ESC/POS (thermal, receipt) printing for Flutter & Dart (Android/iOS)

ESC/POS (thermal, receipt) printing for Flutter & Dart (Android/iOS)

esc_pos_bluetooth The library allows to print receipts using a Bluetooth printer. For WiFi/Ethernet printers, use esc_pos_printer library. TODO (PRs a

Jan 6, 2023

Bluetooth Low Energy library for Flutter with support for simulating peripherals

Bluetooth Low Energy library for Flutter with support for simulating peripherals

FlutterBleLib A library for all your Bluetooth Low Energy needs in Flutter. Internally utilises Polidea's MultiPlatformBleAdapter, which runs on RxAnd

Jan 3, 2023

Flutter blue plus - Flutter plugin for connecting and communicationg with Bluetooth Low Energy devices, on Android and iOS

Flutter blue plus - Flutter plugin for connecting and communicationg with Bluetooth Low Energy devices, on Android and iOS

Introduction FlutterBluePlus is a bluetooth plugin for Flutter, a new app SDK to

Dec 22, 2022

Low-level link (text, URLs, emails) parsing library in Dart

linkify Low-level link (text, URLs, emails) parsing library in Dart. Required Dart =2.12 (has null-safety support). Flutter library. Pub - API Docs -

Nov 4, 2022

The ultimate baby monitor! This mobile app helps new parents keep track of all their newborn baby's needs, milestones, and reminders in one place!

New Parent The ultimate baby monitor! This mobile app helps new parents keep track of all their newborn baby's needs, milestones, and reminders in one

Jun 22, 2022

A Flutter library allows to print receipts using a Bluetooth printer

A Flutter library allows to print receipts using a Bluetooth printer

esc_pos_bluetooth The library allows to print receipts using a Bluetooth printer. For WiFi/Ethernet printers, use esc_pos_printer library. TODO (PRs a

Dec 20, 2021

Flutter library for sending bytes to Bluetooth devices on Android/iOS

fluetooth A new flutter plugin project. Getting Started This project is a starting point for a Flutter plug-in package, a specialized package that inc

Jan 2, 2022

Esp provisioning - A library for Flutter was developed to provide network credentials and/or custom data to an ESP32 over Bluetooth BLE

Esp provisioning - A library for Flutter was developed to provide network credentials and/or custom data to an ESP32 over Bluetooth BLE

esp_provisioning Espressif BLE Provisioning library for ESP32 A library for Flut

Nov 21, 2022

I have created app to connect printer with bluetooth. And I already fix library bugs

flutter_bluetooth_printer A new Flutter application. Getting Started This project is a starting point for a Flutter application. A few resources to ge

May 11, 2022

Magpie-fly is a component library produced by 58 Group, which encapsulates a variety of common components to meet the needs of developers

[toc] magpie_fly Magpie-fly 是58集体出品组件库,封装了多种常用组件,以满足开发者需求。(Magpie-fly is a component library produced by 58 Group, which encapsulates a variety of com

Mar 18, 2022

Flutter's core Dropdown Button widget with steady dropdown menu and many options you can customize to your needs.

Flutter's core Dropdown Button widget with steady dropdown menu and many options you can customize to your needs.

Flutter DropdownButton2 Intro Flutter's core Dropdown Button widget with steady dropdown menu and many options you can customize to your needs. Featur

Jan 4, 2023

With TOT you can find a teacher that is suitable for your needs with less effort, less time, and less money.

With TOT you can find a teacher that is suitable for your needs with less effort,  less time, and less money.

TOT App In TOT we are here to help you find a teacher at any aspect of science you want from kindergarten to secondary schools. Instead of searching m

Sep 29, 2022

🔥 A low-cost Flutter screen adaptation solution (类似今日头条屏幕适配方案,一个极低成本的 Flutter 屏幕适配方案)。

🔥 A low-cost Flutter screen adaptation solution (类似今日头条屏幕适配方案,一个极低成本的 Flutter 屏幕适配方案)。

screen_autosize 🔥 A low-cost Flutter screen adaptation solution (参考今日头条 Android 屏幕适配方案的实现原理,实现的一个极低成本的 Flutter 屏幕适配方案)。 Flutter 屏幕适配方案,可做到 100% 还原设计稿

Dec 17, 2022

A low-cost Flutter screen adaptation solution(一个极低成本的 Flutter 屏幕适配方案)

A low-cost Flutter screen adaptation solution(一个极低成本的 Flutter 屏幕适配方案)

A low-cost Flutter screen adaptation solution(一个极低成本的 Flutter 屏幕适配方案) 100% 还原 UI,只需要按照设计图写的宽高写即可 先看图片,设置的标准宽度是 360 iPhone 8 --------------------------

Sep 27, 2022
Comments
Owner
null
null 5 Nov 21, 2022
I have created app to connect printer with bluetooth. And I already fix library bugs

flutter_bluetooth_printer A new Flutter application. Getting Started This project is a starting point for a Flutter application. A few resources to ge

Bounphone KOSADA 1 May 11, 2022
Bluetooth plugin for Flutter

Introduction FlutterBlue is a bluetooth plugin for Flutter, a new app SDK to help developers build modern multi-platform apps. Alpha version This libr

Paul DeMarco 2.2k Jan 5, 2023
Using Bluetooth plugin in Flutter (flutter_bluetooth_serial)

Flutter Bluetooth NOTE: This is the updated version of the app (using flutter_bluetooth_serial 0.2.2). This version has much fewer bugs and provides a

Souvik Biswas 179 Nov 22, 2022
A Flutter Template to communicate with an esp32 over bluetooth

Flutter Esp32 Bluetooth Template Changes in android/ [1 if you take the code to an other project, 2 still nessesarely]: Change minSdkVersion from 16 t

0x4d/Martin Loretz 23 Dec 20, 2022
This flutter app will help you to connect to Bluetooth Devices (like, HC-05)

Flutter Bluetooth NOTE: This is the updated version of the app (using flutter_bluetooth_serial 0.2.2). This version has much fewer bugs and provides a

Riyad Al-Ali 1 Jun 5, 2022
Flutter basic implementation for Classical Bluetooth (only RFCOMM for now)

flutter_bluetooth_serial Flutter basic implementation for Classical Bluetooth (only RFCOMM for now). Features The first goal of this project, started

null 1 Nov 7, 2022
A project to get data from a fitbit device using bluetooth

Flutter 2 Boilerplate (version 1.3.0) A boilerplate project created in flutter. Boilerplate supports both web and mobile. VSCode is recommended in thi

Vajira Att 0 Dec 16, 2021
EI Blue - Edge Impulse Data Capture Over Bluetooth

EI Blue - Edge Impulse Data Capture Over Bluetooth Purpose of this project is to enable embedded engineers to collect data from bluetooth enabled micr

Mithun Das 4 Dec 21, 2022
Flutter library that handles BLE operations for multiple devices.

Flutter reactive BLE library Flutter library that handles BLE operations for multiple devices. Usage The reactive BLE lib supports the following: BLE

Philips Hue 473 Jan 4, 2023