In this piece we want to look at Flutter bluetooth examples and libraries. How to use these to scan and connect to bluetooth, be it classic or low energy.

(a). flutter_bluetooth_serial

A basic Flutter Bluetooth Serial.

This is a Flutter basic implementation for Classical Bluetooth. Here are it's features:

  • Adapter status monitoring,

  • Turning adapter on and off,

  • Opening settings,

  • Discovering devices (and requesting discoverability),

  • Listing bonded devices and pairing new ones,

  • Connecting to multiple devices at the same time,

  • Sending and recieving data (multiple connections).

This library supports only android.

Step 1: Install it

In your pubspec.yaml add dependency as follows:

Flutter Tutorial - Remove Back Button from AppBar | automaticallyImplyLeading | YouTube #Short

Flutter Tutorial - Remove Back Butt...
Flutter Tutorial - Remove Back Button from AppBar | automaticallyImplyLeading | YouTube #Short
dependencies:
    # ...
    flutter_bluetooth_serial: ^0.2.2

Then pub get it.

# With pub manager
pub get
# or with Flutter
flutter pub get

Step 2: Write Code

Start by importing the flutter_bluetooth_serial:

import 'package:flutter_bluetooth_serial/flutter_bluetooth_serial.dart';

Now create a try-catch block then establish a connection inside it:

try {
    BluetoothConnection connection = await BluetoothConnection.toAddress(address);
    print('Connected to the device');

You can then listen to incoming data:

    connection.input.listen((Uint8List data) {
        print('Data incoming: ${ascii.decode(data)}');

You can also send or output data:

        connection.output.add(data); // Sending data

You can also disconnect from the connection:

        if (ascii.decode(data).contains('!')) {
            connection.finish(); // Closing connection
            print('Disconnecting by local host');
        }
    }).onDone(() {
        print('Disconnected by remote request');
    });

Here's the full code:

try {
    BluetoothConnection connection = await BluetoothConnection.toAddress(address);
    print('Connected to the device');

    connection.input.listen((Uint8List data) {
        print('Data incoming: ${ascii.decode(data)}');
        connection.output.add(data); // Sending data

        if (ascii.decode(data).contains('!')) {
            connection.finish(); // Closing connection
            print('Disconnecting by local host');
        }
    }).onDone(() {
        print('Disconnected by remote request');
    });
}
catch (exception) {
    print('Cannot connect, exception occured');
}

Example

Find examples here

Reference

Find complete reference here