import 'package:flutter/material.dart';
import 'package:flutter_blue/flutter_blue.dart';
import 'package:permission_handler/permission_handler.dart';
class BlueToothList extends StatefulWidget {
const BlueToothList({Key? key}) : super(key: key);
@override
State<BlueToothList> createState() => _BlueToothState();
}
class _BlueToothState extends State<BlueToothList> {
FlutterBlue flutterBlue = FlutterBlue.instance;
bool IsBlueOn=false;
List<BluetoothDevice> devices=[];
var subscription;
void gatListenblue(){
flutterBlue.state.listen((state) {
if(state==BluetoothState.on){
print(">>蓝牙已开启");
setState(() {
IsBlueOn=true;
});
requestBluetoothPermissions();
}else{
print(">>请打开蓝牙");
setState(() {
IsBlueOn=false;
});
}
});
}
Future<void> requestBluetoothPermissions() async {
var status= await Permission.bluetoothScan.request();
if(status.isGranted){
print("已授权 扫码");
}else{
print("扫码授权失败");
}
var connectStatus=await Permission.bluetoothConnect.request();
if(connectStatus.isGranted){
getblueList();
print("已授权 连接");
}else{
print("连接授权失败");
}
}
void getblueList(){
flutterBlue.startScan(timeout: const Duration(seconds: 10));
subscription = flutterBlue.scanResults.listen((results) {
for (ScanResult r in results) {
if(r.device.name.isNotEmpty && !devices.contains(r.device)) {
setState(() {
devices.add(r.device);
});
}
}
});
}
@override
void initState() {
gatListenblue();
super.initState();
}
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
print(">>App is in the background");
if (state == AppLifecycleState.paused) {
flutterBlue.stopScan();
subscription.cancel();
print(">>App is in the background");
} else if (state == AppLifecycleState.resumed) {
print(">>App is in the foreground");
}
}
@override
void dispose() {
flutterBlue.stopScan();
subscription.cancel();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("蓝牙"),
),
body: Padding(
padding:EdgeInsets.fromLTRB(10, 0, 10, 0) ,
child: Column(
children: devices.map((device){
return Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text("${device.name}"),
ElevatedButton(
onPressed:(){
Navigator.of(context).pushNamed('/bluetooth',arguments:{
'device':device
});
print('$device');
},
child: Text("连接"))
],
);
}).toList(),
),
)
);
}
}