Flutter蓝牙信息查询插件bluetooth_info的使用

Flutter蓝牙信息查询插件bluetooth_info的使用

一个用于获取设备蓝牙信息的Flutter插件,例如设备名称(蓝牙名称)、设备地址(MAC地址)和蓝牙状态。

特性

  • 获取移动设备的设备名称(蓝牙名称)。
  • 获取移动设备的设备地址(MAC地址)。
  • 检查移动设备的蓝牙状态(开启/关闭)。

开始使用

要使用此插件,请按照以下步骤操作:

安装

pubspec.yaml文件中添加bluetooth_info作为依赖项。

dependencies:
  flutter:
    sdk: flutter
  bluetooth_info: ^1.0.0  # 替换为实际的插件版本

示例代码

example/lib/main.dart

import 'dart:io';
import 'package:device_info_plus/device_info_plus.dart';
import 'package:flutter/material.dart';
import 'dart:async';
import 'package:permission_handler/permission_handler.dart';
import 'package:flutter/services.dart';
import 'package:bluetooth_info/bluetooth_info.dart';

void main() {
  runApp(MaterialApp(
    home: BluetoothInfoExample(),
  ));
}

class BluetoothInfoExample extends StatefulWidget {
  const BluetoothInfoExample({super.key});

  [@override](/user/override)
  State<BluetoothInfoExample> createState() => _BluetoothInfoExampleState();
}

class _BluetoothInfoExampleState extends State<BluetoothInfoExample> {
  [@override](/user/override)
  void initState() {
    WidgetsBinding.instance.addPostFrameCallback((_) {
      Future.delayed(Duration(milliseconds: 1000), () async {
        await isBTPermissionGiven();
      });
    });
    super.initState();
  }

  // 检查蓝牙权限是否已授予
  Future<bool> isBTPermissionGiven() async {
    if (Platform.isIOS) {
      if (!await Permission.bluetooth.isRestricted) {
        return true;
      } else {
        var response = await [Permission.bluetooth].request();
        return response[Permission.bluetooth]?.isGranted == true;
      }
    } else if (Platform.isAndroid) {
      var isAndroidS = (int.tryParse(
                  (await DeviceInfoPlugin().androidInfo).version.release) ??
              0) >=
          11;
      if (isAndroidS) {
        if (await Permission.bluetoothScan.isGranted) {
          return true;
        } else {
          var response = await [
            Permission.bluetoothScan,
            Permission.bluetoothConnect
          ].request();
          return response[Permission.bluetoothScan]?.isGranted == true &&
              response[Permission.bluetoothConnect]?.isGranted == true;
        }
      } else {
        return true;
      }
    }
    return false;
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Bluetooth Info Example')),
      body: Container(
        child: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              ElevatedButton(
                onPressed: () => _getDeviceName(),
                child: Text('获取设备名称'),
              ),
              ElevatedButton(
                onPressed: () => _getDeviceAddress(),
                child: Text('获取设备地址'),
              ),
              ElevatedButton(
                onPressed: () => _checkBluetoothStatus(),
                child: Text('检查蓝牙状态'),
              ),
            ],
          ),
        ),
      ),
    );
  }

  // 获取设备名称
  void _getDeviceName() async {
    String deviceName = await BluetoothInfo.getDeviceName();
    print('设备名称: $deviceName');
  }

  // 获取设备地址
  void _getDeviceAddress() async {
    String deviceAddress = await BluetoothInfo.getDeviceAddress();
    print('设备地址: $deviceAddress');
  }

  // 检查蓝牙状态
  void _checkBluetoothStatus() async {
    bool isBluetoothEnabled = await BluetoothInfo.isBluetoothEnabled();
    print('蓝牙已启用: $isBluetoothEnabled');
  }
}

更多关于Flutter蓝牙信息查询插件bluetooth_info的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter蓝牙信息查询插件bluetooth_info的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


bluetooth_info 是一个用于在 Flutter 应用中查询蓝牙信息的插件。它可以帮助你获取设备的蓝牙状态、已配对设备列表、已连接设备信息等。以下是如何在 Flutter 项目中使用 bluetooth_info 插件的步骤和示例代码。

1. 添加依赖

首先,你需要在 pubspec.yaml 文件中添加 bluetooth_info 插件的依赖:

dependencies:
  flutter:
    sdk: flutter
  bluetooth_info: ^1.0.0  # 请使用最新版本

然后运行 flutter pub get 来安装依赖。

2. 导入插件

在你的 Dart 文件中导入 bluetooth_info 插件:

import 'package:bluetooth_info/bluetooth_info.dart';

3. 获取蓝牙状态

你可以使用 BluetoothInfo 类来获取蓝牙的状态:

void checkBluetoothState() async {
  BluetoothState state = await BluetoothInfo.bluetoothState;
  print('Bluetooth state: $state');
}

BluetoothState 是一个枚举类型,可能的值包括 unknownunavailableunauthorizedturningOnonturningOffoff

4. 获取已配对设备列表

你可以获取已配对的蓝牙设备列表:

void getPairedDevices() async {
  List<BluetoothDevice> devices = await BluetoothInfo.pairedDevices;
  for (var device in devices) {
    print('Paired device: ${device.name}, ${device.address}');
  }
}

BluetoothDevice 类包含设备的名称 (name) 和地址 (address)。

5. 获取已连接设备列表

你可以获取当前已连接的蓝牙设备列表:

void getConnectedDevices() async {
  List<BluetoothDevice> devices = await BluetoothInfo.connectedDevices;
  for (var device in devices) {
    print('Connected device: ${device.name}, ${device.address}');
  }
}

6. 监听蓝牙状态变化

你可以监听蓝牙状态的变化:

void listenBluetoothState() {
  BluetoothInfo.onStateChanged.listen((BluetoothState state) {
    print('Bluetooth state changed: $state');
  });
}

7. 请求蓝牙权限

在某些平台上,你可能需要请求蓝牙权限。你可以使用 permission_handler 插件来请求权限:

import 'package:permission_handler/permission_handler.dart';

void requestBluetoothPermissions() async {
  var status = await Permission.bluetooth.request();
  if (status.isGranted) {
    print('Bluetooth permission granted');
  } else {
    print('Bluetooth permission denied');
  }
}

8. 完整示例

以下是一个完整的示例,展示了如何使用 bluetooth_info 插件获取蓝牙状态、已配对设备和已连接设备:

import 'package:flutter/material.dart';
import 'package:bluetooth_info/bluetooth_info.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: BluetoothInfoScreen(),
    );
  }
}

class BluetoothInfoScreen extends StatefulWidget {
  [@override](/user/override)
  _BluetoothInfoScreenState createState() => _BluetoothInfoScreenState();
}

class _BluetoothInfoScreenState extends State<BluetoothInfoScreen> {
  String _bluetoothState = 'Unknown';
  List<BluetoothDevice> _pairedDevices = [];
  List<BluetoothDevice> _connectedDevices = [];

  [@override](/user/override)
  void initState() {
    super.initState();
    _checkBluetoothState();
    _getPairedDevices();
    _getConnectedDevices();
    _listenBluetoothState();
  }

  void _checkBluetoothState() async {
    BluetoothState state = await BluetoothInfo.bluetoothState;
    setState(() {
      _bluetoothState = state.toString();
    });
  }

  void _getPairedDevices() async {
    List<BluetoothDevice> devices = await BluetoothInfo.pairedDevices;
    setState(() {
      _pairedDevices = devices;
    });
  }

  void _getConnectedDevices() async {
    List<BluetoothDevice> devices = await BluetoothInfo.connectedDevices;
    setState(() {
      _connectedDevices = devices;
    });
  }

  void _listenBluetoothState() {
    BluetoothInfo.onStateChanged.listen((BluetoothState state) {
      setState(() {
        _bluetoothState = state.toString();
      });
    });
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Bluetooth Info'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text('Bluetooth State: $_bluetoothState'),
            SizedBox(height: 20),
            Text('Paired Devices:'),
            for (var device in _pairedDevices)
              Text('${device.name} - ${device.address}'),
            SizedBox(height: 20),
            Text('Connected Devices:'),
            for (var device in _connectedDevices)
              Text('${device.name} - ${device.address}'),
          ],
        ),
      ),
    );
  }
}
回到顶部