flutter 蓝牙搜索 读数据 写入数据 01

131 阅读1分钟
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
  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) {
     // do something with scan 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() {
    // TODO: implement dispose
    // Stop scanning
    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(),
          ),
      )
    );
  }
}