bluetooth_link 0.0.4 copy "bluetooth_link: ^0.0.4" to clipboard
bluetooth_link: ^0.0.4 copied to clipboard

PlatformAndroid

bluetooth_link is a Flutter plugin that enables communication with classic Bluetooth (SPP) devices on Android. Supports device discovery, connection, data streaming, and disconnection.

example/lib/main.dart

import 'package:flutter/material.dart';
import 'dart:async';
import 'package:flutter/services.dart';
import 'package:bluetooth_link/bluetooth_link.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});
  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      home: BluetoothTestScreen(),
    );
  }
}

class BluetoothTestScreen extends StatefulWidget {
  const BluetoothTestScreen({super.key});

  @override
  State<BluetoothTestScreen> createState() => _BluetoothTestScreenState();
}

class _BluetoothTestScreenState extends State<BluetoothTestScreen> {
  List<Map<String, String>> devices = [];
  bool connected = false;
  String received = '';
  StreamSubscription? _streamSub;

  @override
  void initState() {
    super.initState();
    _loadBondedDevices();
  }

  Future<void> _loadBondedDevices() async {
    try {
      final result = await BluetoothLink.getBondedDevices();
      setState(() {
        devices = List<Map<String, String>>.from(result);
      });
    } on PlatformException catch (e) {
      debugPrint("Error: ${e.message}");
    }
  }

  Future<void> _connect(String address) async {
    try {
      final result = await BluetoothLink.connect(address);
      debugPrint(result);
      setState(() => connected = true);
      _streamSub = BluetoothLink.dataStream.listen((event) {
        final type = event['type'];
        if (type == 'data') {
          final data = event['data'];
          print('Received: $data');
        } else if (type == 'error') {
          print('Error: ${event['message']}');
        } else if (type == 'disconnected') {
          print('Disconnected: ${event['message']}');
        }
      });
    } on PlatformException catch (e) {
      debugPrint("Connect Error: ${e.message}");
    }
  }

  Future<void> _disconnect() async {
    await BluetoothLink.disconnect();
    await _streamSub?.cancel();
    setState(() {
      connected = false;
      received = '';
    });
  }

  @override
  void dispose() {
    _disconnect();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Bluetooth Link Test')),
      body: Column(
        children: [
          if (!connected) ...[
            const SizedBox(height: 16),
            const Text("Bonded Devices",
                style: TextStyle(fontWeight: FontWeight.bold)),
            Expanded(
              child: ListView.builder(
                itemCount: devices.length,
                itemBuilder: (_, index) {
                  final dev = devices[index];
                  return ListTile(
                    title: Text(dev['name'] ?? 'Unknown'),
                    subtitle: Text(dev['address'] ?? ''),
                    onTap: () => _connect(dev['address']!),
                  );
                },
              ),
            ),
          ] else ...[
            const SizedBox(height: 16),
            Text("Connected. Receiving data:",
                style: const TextStyle(fontWeight: FontWeight.bold)),
            Expanded(
              child: SingleChildScrollView(
                child: Text(received, style: const TextStyle(fontSize: 16)),
              ),
            ),
            ElevatedButton(
              onPressed: _disconnect,
              child: const Text("Disconnect"),
              style: ElevatedButton.styleFrom(backgroundColor: Colors.red),
            ),
          ]
        ],
      ),
    );
  }
}
0
likes
150
points
12
downloads

Publisher

unverified uploader

Weekly Downloads

bluetooth_link is a Flutter plugin that enables communication with classic Bluetooth (SPP) devices on Android. Supports device discovery, connection, data streaming, and disconnection.

Documentation

API reference

License

MIT (license)

Dependencies

flutter, plugin_platform_interface

More

Packages that depend on bluetooth_link

Packages that implement bluetooth_link