### Flutter Bluetooth Classic Example App Setup Source: https://pub.dev/packages/flutter_classic_bluetooth/example This snippet shows the main entry point for the example application. It sets up the MaterialApp with themes and navigation destinations, initializing the BluetoothController and handling lifecycle events. ```dart import 'package:flutter/material.dart'; import 'controller.dart'; import 'pages/capabilities_page.dart'; import 'pages/dashboard_page.dart'; import 'pages/discover_page.dart'; import 'pages/paired_page.dart'; import 'pages/server_page.dart'; import 'widgets.dart'; void main() => runApp(const BluetoothExampleApp()); class BluetoothExampleApp extends StatelessWidget { const BluetoothExampleApp({super.key}); ThemeData _theme(Brightness brightness) { final scheme = ColorScheme.fromSeed( seedColor: const Color(0xFF2962FF), brightness: brightness, ); return ThemeData( colorScheme: scheme, useMaterial3: true, cardTheme: const CardThemeData( elevation: 0, margin: EdgeInsets.zero, clipBehavior: Clip.antiAlias, ), cardColor: scheme.surfaceContainerLow, appBarTheme: AppBarTheme( backgroundColor: scheme.surface, scrolledUnderElevation: 2, ), ); } @override Widget build(BuildContext context) { return MaterialApp( title: 'Bluetooth Classic', debugShowCheckedModeBanner: false, theme: _theme(Brightness.light), darkTheme: _theme(Brightness.dark), home: const HomeShell(), ); } } class _Destination { const _Destination(this.label, this.icon, this.selectedIcon); final String label; final IconData icon; final IconData selectedIcon; } class HomeShell extends StatefulWidget { const HomeShell({super.key}); @override State createState() => _HomeShellState(); } class _HomeShellState extends State with WidgetsBindingObserver { final _controller = BluetoothController(); int _index = 0; static const _destinations = [ _Destination('Dashboard', Icons.dashboard_outlined, Icons.dashboard), _Destination('Discover', Icons.radar_outlined, Icons.radar), _Destination('Paired', Icons.devices_outlined, Icons.devices), _Destination('Server', Icons.dns_outlined, Icons.dns), _Destination('About', Icons.fact_check_outlined, Icons.fact_check), ]; @override void initState() { super.initState(); WidgetsBinding.instance.addObserver(this); _controller.addListener(_onControllerChanged); _controller.init(); } @override void didChangeAppLifecycleState(AppLifecycleState state) { // Re-sync the adapter state when returning to the app, in case the user // toggled Bluetooth from the system while we were backgrounded. if (state == AppLifecycleState.resumed) { _controller.refreshAdapterState(); } } void _onControllerChanged() { final error = _controller.lastError; if (error != null && mounted) { ScaffoldMessenger.of(context).showSnackBar( SnackBar(content: Text(error), behavior: SnackBarBehavior.floating), ); _controller.clearError(); } } @override void dispose() { WidgetsBinding.instance.removeObserver(this); _controller.removeListener(_onControllerChanged); _controller.dispose(); super.dispose(); } Widget _page(int i) { switch (i) { case 0: return DashboardPage( controller: _controller, onNavigate: (i) => setState(() => _index = i), ); case 1: return DiscoverPage(controller: _controller); case 2: return PairedPage(controller: _controller); case 3: return ServerPage(controller: _controller); default: return CapabilitiesPage(controller: _controller); } } ``` -------------------------------- ### Add Dependency to pubspec.yaml Source: https://pub.dev/packages/flutter_classic_bluetooth/install This is an example of how the flutter_classic_bluetooth dependency will appear in your pubspec.yaml file after running the add command. ```yaml dependencies: flutter_classic_bluetooth: ^0.1.2 ``` -------------------------------- ### Linux Bluetooth Development Packages Source: https://pub.dev/packages/flutter_classic_bluetooth Install necessary development packages for GTK and BlueZ on Debian/Ubuntu systems for native plugin builds. ```bash sudo apt-get install -y libgtk-3-dev libbluetooth-dev ninja-build cmake pkg-config clang ``` -------------------------------- ### Run an RFCOMM Bluetooth Server Source: https://pub.dev/packages/flutter_classic_bluetooth Starts an RFCOMM server to accept incoming Bluetooth connections. It listens for clients, processes incoming data, and sends responses. Remember to close the server when it's no longer needed. ```dart final server = await bluetooth.startServer( serviceName: 'MyService', uuid: BtcUuid.spp, // optional — SPP is the default secure: true, ); server.connections.listen((client) { print('Client connected: ${client.address}'); client.input.listen((data) => client.output.writeString('echo: ')); }); // ...later await server.close(); ``` -------------------------------- ### Import flutter_classic_bluetooth in Dart Source: https://pub.dev/packages/flutter_classic_bluetooth/install Import the package into your Dart files to start using its functionalities. This line should be placed at the top of your Dart file. ```dart import 'package:flutter_classic_bluetooth/flutter_classic_bluetooth.dart'; ``` -------------------------------- ### Discover Nearby Bluetooth Devices Source: https://pub.dev/packages/flutter_classic_bluetooth Starts discovering nearby Bluetooth devices and listens for results. Remember to stop discovery and cancel the subscription when done to free up resources. ```dart final sub = bluetooth.discoveryResults.listen((device) { print('Found: ${device.displayName} (${device.address})'); }); await bluetooth.startDiscovery(); // ...later await bluetooth.stopDiscovery(); await sub.cancel(); ``` -------------------------------- ### Initialize and Check Bluetooth Support Source: https://pub.dev/packages/flutter_classic_bluetooth Initializes the Bluetooth instance and checks if the platform supports Bluetooth, if it's enabled, and retrieves platform capabilities. Use this to ensure Bluetooth is available before proceeding. ```dart final bluetooth = FlutterClassicBluetooth(); final supported = await bluetooth.isSupported(); final enabled = await bluetooth.isEnabled(); final caps = await bluetooth.getPlatformCapabilities(); if (caps.canDiscoverDevices) { // safe to call startDiscovery() on this platform } ``` -------------------------------- ### Build UI for Bluetooth Classic App Source: https://pub.dev/packages/flutter_classic_bluetooth/example This widget builds the main UI for the Bluetooth Classic application, including an AppBar, body content that adapts to screen width, and bottom navigation. ```dart @override Widget build(BuildContext context) { return LayoutBuilder( builder: (context, constraints) { final wide = constraints.maxWidth >= 720; return Scaffold( appBar: AppBar( title: const Text('Bluetooth Classic'), actions: [ ListenableBuilder( listenable: _controller, builder: (context, _) { final v = adapterVisual( _controller.adapterState, Theme.of(context).colorScheme, ); return Padding( padding: const EdgeInsets.only(right: 12), child: Center( child: StatusPill( label: v.label, color: v.color, icon: v.icon, ), ), ); }, ), ], ), body: ListenableBuilder( listenable: _controller, builder: (context, _) { if (!_controller.ready) { return const Center(child: CircularProgressIndicator()); } final content = _page(_index); if (!wide) return content; return Row( children: [ NavigationRail( selectedIndex: _index, onDestinationSelected: (i) => setState(() => _index = i), labelType: NavigationRailLabelType.all, destinations: [ for (final d in _destinations) NavigationRailDestination( icon: Icon(d.icon), selectedIcon: Icon(d.selectedIcon), label: Text(d.label), ), ], ), const VerticalDivider(width: 1), Expanded(child: content), ], ); }, ), bottomNavigationBar: wide ? null : NavigationBar( selectedIndex: _index, onDestinationSelected: (i) => setState(() => _index = i), destinations: [ for (final d in _destinations) NavigationDestination( icon: Icon(d.icon), selectedIcon: Icon(d.selectedIcon), label: d.label, ), ], ), ); }, ); } } ``` -------------------------------- ### MIT License Source: https://pub.dev/packages/flutter_classic_bluetooth/license This is the MIT License text. It grants broad permissions for using, copying, modifying, merging, publishing, distributing, and selling the software, provided the copyright notice and permission notice are included. ```plaintext MIT License Copyright (c) 2026 Masum Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ``` -------------------------------- ### iOS Bluetooth Configuration Source: https://pub.dev/packages/flutter_classic_bluetooth Declare supported MFi protocols and a Bluetooth usage description in your iOS Info.plist file. ```xml UISupportedExternalAccessoryProtocols com.example.spp NSBluetoothAlwaysUsageDescription This app communicates with Bluetooth accessories. ``` -------------------------------- ### Add flutter_classic_bluetooth Dependency Source: https://pub.dev/packages/flutter_classic_bluetooth/install Use this command to add the package to your Flutter project's dependencies. This command automatically updates your pubspec.yaml file. ```bash $ flutter pub add flutter_classic_bluetooth ``` -------------------------------- ### Connect to a Bluetooth Device Source: https://pub.dev/packages/flutter_classic_bluetooth Establishes a connection to a Bluetooth device using its address. Supports default SPP connection and custom configurations with specific UUIDs, security settings, and timeouts. ```dart // SPP is the default — for HC-05/06, ESP32, Arduino, etc. this is all you need: final connection = await bluetooth.connect(address: 'AA:BB:CC:DD:EE:FF'); print('Connected: id=${connection.id}'); // Override the UUID and tune the attempt only when you need to: final custom = await bluetooth.connect( address: 'AA:BB:CC:DD:EE:FF', uuid: BtcUuid.spp, // or any service UUID string secure: true, timeout: const Duration(seconds: 15), // optional ); ``` -------------------------------- ### macOS Bluetooth Entitlement Source: https://pub.dev/packages/flutter_classic_bluetooth Add the Bluetooth entitlement to your macOS project's .entitlements file and a usage string to Info.plist. ```xml com.apple.security.device.bluetooth ``` -------------------------------- ### Handle Bluetooth Classic Exceptions Source: https://pub.dev/packages/flutter_classic_bluetooth This snippet demonstrates how to use a try-catch block to handle specific Bluetooth Classic exceptions thrown by the flutter_classic_bluetooth package. It covers unsupported features, disabled Bluetooth, timeouts, and general connection errors. ```dart try { await bluetooth.connect(address: addr, uuid: uuid); } on BtcUnsupportedException catch (e) { print('${e.feature} not supported on ${e.platform}'); } on BtcDisabledException { print('Turn on Bluetooth first'); } on BtcTimeoutException { print('Connection timed out'); } on BtcConnectionException catch (e) { print('Connection failed: ${e.message}'); } on BtcException catch (e) { print('Bluetooth error: ${e.message}'); } ``` -------------------------------- ### Android Bluetooth Permissions Source: https://pub.dev/packages/flutter_classic_bluetooth Add these Bluetooth and location permissions to your AndroidManifest.xml file for different Android versions. ```xml ``` -------------------------------- ### Pair and Unpair Bluetooth Devices Source: https://pub.dev/packages/flutter_classic_bluetooth Manages the bonding process for Bluetooth devices, allowing pairing if the platform supports it and listening for bond state changes. Unpairing is also supported. ```dart if (caps.canBondDevices) { final ok = await bluetooth.bondDevice('AA:BB:CC:DD:EE:FF'); print('Bonded: $ok'); } bluetooth.bondState('AA:BB:CC:DD:EE:FF').listen((state) { print('Bond state: ${state.name}'); }); await bluetooth.unbondDevice('AA:BB:CC:DD:EE:FF'); ``` -------------------------------- ### List Paired Bluetooth Devices Source: https://pub.dev/packages/flutter_classic_bluetooth Retrieves a list of all devices that have been previously paired with the system. Displays their display name, address, and bond state. ```dart final devices = await bluetooth.getPairedDevices(); for (final device in devices) { print('${device.displayName} — ${device.address} [${device.bondState.name}]'); } ``` -------------------------------- ### Control Bluetooth Adapter State Source: https://pub.dev/packages/flutter_classic_bluetooth Monitors the state of the Bluetooth adapter and provides controls to enable Bluetooth or set discoverability if the platform capabilities allow. ```dart bluetooth.adapterState.listen((state) { print('Adapter: ${state.name}'); // on, off, turningOn, ... }); if (caps.canEnableBluetooth) { await bluetooth.enableBluetooth(); // Android: shows the system dialog } if (caps.canSetDiscoverable) { await bluetooth.setDiscoverable(120); // seconds } ``` -------------------------------- ### Receive Data from a Bluetooth Connection Source: https://pub.dev/packages/flutter_classic_bluetooth Listens for incoming data on an established Bluetooth connection. The stream provides data as Uint8List and signals when the remote connection is closed. ```dart connection.input.listen( (Uint8List data) => print('Received ${data.length} bytes: $data'), onDone: () => print('Remote closed the connection'), ); ``` -------------------------------- ### Automatic Bluetooth Reconnection Source: https://pub.dev/packages/flutter_classic_bluetooth Maintains a persistent Bluetooth link by automatically reconnecting upon drops. Provides stable input and state streams, allowing a single subscription for the lifetime of the link. ```dart final link = bluetooth.connectWithReconnect( address: 'AA:BB:CC:DD:EE:FF', policy: const BtcReconnectPolicy( maxAttempts: null, // retry forever (default) initialBackoff: Duration(seconds: 1), maxBackoff: Duration(seconds: 30), ), ); link.state.listen((s) => print('Link: ${s.name}')); // connecting/connected/reconnecting/… link.input.listen((bytes) => print('RX ${bytes.length} bytes')); if (link.isConnected) await link.sendString('PING\r\n'); // ...when done await link.close(); // stop reconnecting and release everything ``` -------------------------------- ### Send Data Over a Bluetooth Connection Source: https://pub.dev/packages/flutter_classic_bluetooth Sends data to a connected Bluetooth device. Supports sending raw bytes, writing strings, and ensures all queued data is sent before proceeding. ```dart // Raw bytes await connection.output.add(Uint8List.fromList([0x01, 0x02, 0x03])); // Convenience helpers await connection.output.writeBytes([0x04, 0x05]); await connection.output.writeString('AT+RESET\r\n'); // Wait until everything queued so far has been written await connection.output.allSent; ``` -------------------------------- ### Disconnect and Dispose Bluetooth Connection Source: https://pub.dev/packages/flutter_classic_bluetooth Gracefully disconnects from a Bluetooth device, flushing any pending writes, or disconnects immediately. Always dispose of the connection to release resources. ```dart await connection.finish(); // flush pending writes, then disconnect // or: await connection.close(); // disconnect immediately connection.dispose(); // always release resources when done ``` -------------------------------- ### Watch Bluetooth Connection State Source: https://pub.dev/packages/flutter_classic_bluetooth Monitors the state of an active Bluetooth connection. The stream emits connection states like 'connected', 'disconnecting', and 'disconnected'. Also checks the current connection status. ```dart connection.stateStream.listen((state) { print('State: ${state.name}'); // connected, disconnecting, disconnected, ... }); print(connection.isConnected); // true while connected ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.