flutter使用flutter_ble_plus插件运用流的方式,显示蓝牙扫描结果页面
import 'package:flutter/material.dart';
import 'package:flutter_ble_plus/flutter_ble_plus.dart';
class BluetoothScanPage extends StatefulWidget {
@override
_BluetoothScanPageState createState() => _BluetoothScanPageState();
}
class _BluetoothScanPageState extends State<BluetoothScanPage> {
Stream<BluetoothScanResult>? _scanStream;
bool _isScanning = false;
void startScan() async {
if (_isScanning) return;
setState(() {
_isScanning = true;
});
_scanStream = FlutterBlePlus.scanResults.doOnDone(() {
setState(() {
_isScanning = false;
});
});
await FlutterBlePlus.startScan(timeout: 5);
}
void stopScan() async {
await FlutterBlePlus.stopScan();
setState(() {
_scanStream = null;
_isScanning = false;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('蓝牙扫描结果'),
actions: [
IconButton(
icon: Icon(_isScanning ? Icons.stop : Icons.search),
onPressed: _isScanning ? stopScan : startScan,
),
],
),
body: StreamBuilder<BluetoothScanResult>(
stream: _scanStream,
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.active) {
final results = snapshot.data?.results ?? [];
return ListView.builder(
itemCount: results.length,
itemBuilder: (context, index) {
final result = results[index];
return ListTile(
title: Text(result.device.name ?? 'Unknown Device'),
subtitle: Text(result.device.id.toString()),
// 可以在这里添加更多的设备信息
);
},
);
}
return Center(
child: _isScanning
? CircularProgressIndicator()
: Text('Press search button to start scanning'),
);
},
),
);
}
}
这段代码首先定义了一个BluetoothScanPage
页面,它使用StreamBuilder
来构建界面,以便实时显示扫描结果。startScan
方法开始扫描,stopScan
方法停止扫描,并通过_isScanning
标志控制搜索按钮的状态。扫描结果通过_scanStream
这个Stream<BluetoothScanResult>
进行展示,其中BluetoothScanResult
是扫描结果的类型。这个例子展示了如何在Flutter中使用流的方式来处理蓝牙设备的扫描结果,并且实现了界面的实时更新。
评论已关闭