How to pair a BLE device with a phone using Flutter and flutter_blue package?

I’m developing a Flutter application where I need to connect and pair a Bluetooth Low Energy (BLE) device with a phone. I’m using the flutter_blue package for Bluetooth connectivity. While I can scan for devices and connect to them, I’m struggling with how to handle the pairing process.

Here’s a snippet of my code for scanning and connecting to devices:

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

class BluetoothLEManager extends StatefulWidget {
  const BluetoothLEManager({Key? key}) : super(key: key);

  @override
  BluetoothLEManagerState createState() => BluetoothLEManagerState();
}

class BluetoothLEManagerState extends State<BluetoothLEManager> with SingleTickerProviderStateMixin {
  FlutterBlue flutterBlue = FlutterBlue.instance;
  List<BluetoothDevice> _devices = [];
  bool _isSearching = false;
  bool _scanCompleted = false;

  @override
  void initState() {
    super.initState();
    startBluetoothScan(isInitialScan: true);
  }

  @override
  void dispose() {
    flutterBlue.stopScan();
    super.dispose();
  }

  void startBluetoothScan({bool isInitialScan = false}) {
    if (_isSearching) return;

    setState(() {
      _isSearching = true;
      _scanCompleted = false;
    });

    flutterBlue.startScan(timeout: const Duration(seconds: 10)).then((_) {
      setState(() {
        _isSearching = false;
        _scanCompleted = true;
      });
    });

    flutterBlue.scanResults.listen((results) {
      setState(() {
        _devices = results.map((r) => r.device).where((device) => device.name.isNotEmpty).toList();
      });
    });

    flutterBlue.isScanning.listen((isScanning) {
      if (!isScanning) {
        print('Scanning stopped');
      }
    });
  }

  Future<void> connectToDevice(BluetoothDevice device) async {
    await device.connect();
    // further code to handle connection and service discovery
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('BLE Devices'),
      ),
      body: ListView.builder(
        itemCount: _devices.length,
        itemBuilder: (context, index) {
          return ListTile(
            title: Text(_devices[index].name),
            onTap: () => connectToDevice(_devices[index]),
          );
        },
      ),
    );
  }
}

How do I pair a BLE device with the phone using the flutter_blue package and is there a specific method or process I should follow to ensure the device is paired before establishing a connection?

Any guidance or example code would be greatly appreciated.

(What I’ve tried below)

Attempt to Check Bond State and Pair:

I tried to check the bond state of the device and initiate pairing if the device was not already paired. The code snippet I used was:

Future<void> checkAndPairDevice(BluetoothDevice device) async {
  final BondState bondState = await device.bondState.first;

  if (bondState == BondState.bonded) {
    print('Device is already paired');
  } else {
    print('Device is not paired. Attempting to pair...');
    try {
      await device.pair();
      print('Pairing successful');
    } catch (error) {
      print('Pairing failed: $error');
      return;
    }
  }
}

Unfortunately, this approach did not work because the flutter_blue package does not support the bondState and pair methods directly. I encountered errors indicating these methods were undefined.

Switching to flutter_blue_plus Package:

I attempted to switch to the flutter_blue_plus package, which has more features and active maintenance. However, this resulted in numerous type conflicts and compatibility issues between flutter_blue and flutter_blue_plus types, making it impractical to integrate both packages.

Manual Pairing:

I also considered manually prompting the user to pair the devices via the system’s Bluetooth settings before initiating the connection in the app. However, this approach does not provide a seamless user experience and does not ensure the app can programmatically verify and handle pairing.

New contributor

DOUINA Mouhamed is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật