bluetooth_connect 0.0.2
bluetooth_connect: ^0.0.2 copied to clipboard
Android / iOS BLE 扫描与连接。iOS 同时支持 CocoaPods 与 SPM(Swift Package Manager)依赖管理。
example/lib/main.dart
import 'dart:async';
import 'package:bluetooth_connect/bluetooth_connect.dart';
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatefulWidget {
const MyApp({super.key});
@override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
final _bluetooth = BluetoothConnect();
String _status = 'unknown';
List<BluetoothDevice> _devices = [];
StreamSubscription? _scanSub;
@override
void initState() {
super.initState();
_init();
}
Future<void> _init() async {
final available = await _bluetooth.isAvailable();
final on = await _bluetooth.isOn();
setState(() {
_status = 'available=$available, on=$on';
});
_scanSub = _bluetooth.scanResults.listen((list) {
setState(() => _devices = list);
});
}
@override
void dispose() {
_scanSub?.cancel();
super.dispose();
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: const Text('bluetooth_connect example')),
body: Column(
children: [
Padding(
padding: const EdgeInsets.all(16),
child: Text('Status: $_status'),
),
ElevatedButton(
onPressed: () => _bluetooth.startScan(),
child: const Text('Start Scan'),
),
Expanded(
child: ListView.builder(
itemCount: _devices.length,
itemBuilder: (_, i) {
final d = _devices[i];
return ListTile(
title: Text(d.name.isEmpty ? 'Unknown' : d.name),
subtitle: Text('${d.id} rssi=${d.rssi}'),
trailing: TextButton(
onPressed: () => _bluetooth.connect(d.id),
child: const Text('Connect'),
),
);
},
),
),
],
),
),
);
}
}