classic_bluetooth_flutter 1.0.0 copy "classic_bluetooth_flutter: ^1.0.0" to clipboard
classic_bluetooth_flutter: ^1.0.0 copied to clipboard

PlatformAndroidiOS
unlisted

A Flutter plugin that provides Bluetooth Classic functionality for both Android and iOS platforms, supporting device discovery, connection, and data transfer.

example/lib/main.dart

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

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

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Classic Bluetooth Example',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.blue),
        useMaterial3: true,
      ),
      home: const BluetoothExamplePage(),
    );
  }
}

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

  @override
  State<BluetoothExamplePage> createState() => _BluetoothExamplePageState();
}

class _BluetoothExamplePageState extends State<BluetoothExamplePage> {
  final FlutterBluetoothClassic _bluetooth = FlutterBluetoothClassic();
  final List<BluetoothDevice> _devices = [];
  final TextEditingController _messageController = TextEditingController();
  String _status = 'Initializing...';
  String _receivedData = '';
  BluetoothDevice? _connectedDevice;

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

  Future<void> _initializeBluetooth() async {
    try {
      // Check if Bluetooth is supported
      bool isSupported = await _bluetooth.isBluetoothSupported();
      if (!isSupported) {
        setState(() => _status = 'Bluetooth not supported');
        return;
      }

      // Setup listeners
      _setupBluetoothListeners();

      // Check if Bluetooth is enabled
      bool isEnabled = await _bluetooth.isBluetoothEnabled();
      if (!isEnabled) {
        setState(() => _status = 'Bluetooth is disabled');
        // Try to enable Bluetooth
        await _bluetooth.enableBluetooth();
      } else {
        setState(() => _status = 'Bluetooth is ready');
      }

      // Get paired devices
      final pairedDevices = await _bluetooth.getPairedDevices();
      setState(() => _devices.addAll(pairedDevices));
    } catch (e) {
      setState(() => _status = 'Error: $e');
    }
  }

  void _setupBluetoothListeners() {
    _bluetooth.onStateChanged.listen((state) {
      setState(() => _status = 'Bluetooth ${state.status}');
    });

    _bluetooth.onConnectionChanged.listen((connection) {
      setState(() {
        _status = connection.status;
        if (!connection.isConnected) {
          _connectedDevice = null;
        }
      });
    });

    _bluetooth.onDataReceived.listen((data) {
      setState(() {
        _receivedData += '${data.asString()}\n';
      });
    });
  }

  Future<void> _startDiscovery() async {
    try {
      setState(() {
        _status = 'Scanning for devices...';
        _devices.clear();
      });

      await _bluetooth.startDiscovery();
    } catch (e) {
      setState(() => _status = 'Scan error: $e');
    }
  }

  Future<void> _connect(BluetoothDevice device) async {
    try {
      setState(() => _status = 'Connecting to ${device.name}...');
      await _bluetooth.connect(device.address);
      setState(() => _connectedDevice = device);
    } catch (e) {
      setState(() => _status = 'Connection error: $e');
    }
  }

  Future<void> _sendMessage() async {
    if (_messageController.text.isEmpty) return;

    try {
      await _bluetooth.sendString(_messageController.text);
      _messageController.clear();
    } catch (e) {
      setState(() => _status = 'Send error: $e');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Bluetooth Example'),
        actions: [
          IconButton(
            icon: const Icon(Icons.refresh),
            onPressed: _startDiscovery,
          ),
        ],
      ),
      body: Column(
        children: [
          Padding(
            padding: const EdgeInsets.all(8.0),
            child:
                Text(_status, style: Theme.of(context).textTheme.titleMedium),
          ),
          Expanded(
            child: ListView.builder(
              itemCount: _devices.length,
              itemBuilder: (context, index) {
                final device = _devices[index];
                final isConnected = _connectedDevice?.address == device.address;
                return ListTile(
                  leading: Icon(
                    isConnected ? Icons.bluetooth_connected : Icons.bluetooth,
                    color: isConnected ? Colors.blue : null,
                  ),
                  title: Text(device.name),
                  subtitle: Text(device.address),
                  trailing: ElevatedButton(
                    onPressed: isConnected ? null : () => _connect(device),
                    child: Text(isConnected ? 'Connected' : 'Connect'),
                  ),
                );
              },
            ),
          ),
          if (_connectedDevice != null) ...[
            Expanded(
              child: Padding(
                padding: const EdgeInsets.all(8.0),
                child: SingleChildScrollView(
                  child: Text(_receivedData),
                ),
              ),
            ),
            Padding(
              padding: const EdgeInsets.all(8.0),
              child: Row(
                children: [
                  Expanded(
                    child: TextField(
                      controller: _messageController,
                      decoration: const InputDecoration(
                        hintText: 'Type a message',
                        border: OutlineInputBorder(),
                      ),
                    ),
                  ),
                  const SizedBox(width: 8),
                  IconButton(
                    icon: const Icon(Icons.send),
                    onPressed: _sendMessage,
                  ),
                ],
              ),
            ),
          ],
        ],
      ),
    );
  }

  @override
  void dispose() {
    _bluetooth.dispose();
    _messageController.dispose();
    super.dispose();
  }
}
0
likes
150
points
26
downloads

Publisher

unverified uploader

Weekly Downloads

A Flutter plugin that provides Bluetooth Classic functionality for both Android and iOS platforms, supporting device discovery, connection, and data transfer.

Repository (GitHub)
View/report issues

Documentation

Documentation
API reference

License

MIT (license)

Dependencies

flutter

More

Packages that depend on classic_bluetooth_flutter