Flutter蓝牙启用管理插件bluetooth_enable的使用

Flutter蓝牙启用管理插件bluetooth_enable的使用

简介

BluetoothEnable 是一个为 Flutter 开发者设计的蓝牙插件,用于在应用程序中通过编程方式请求开启蓝牙。
此插件旨在允许开发者自定义其应用的工作流程,以便在请求权限时更加灵活。
该插件目前仅支持 Android 平台。


使用方法

启用蓝牙

首先,需要导入 bluetooth_enable 插件并调用其方法来请求开启蓝牙。

import 'package:bluetooth_enable/bluetooth_enable.dart';

// 请求打开蓝牙
BluetoothEnable.enableBluetooth.then((value) {
  if (value == "true") {
    // 蓝牙已成功开启
  } else if (value == "false") {
    // 蓝牙未开启
  }
});

使用自定义弹窗启用蓝牙

此方法允许开发者在 Dart 层面调用一个自定义弹窗。根据用户的操作,蓝牙可以手动开启,或者弹窗关闭而无进一步操作。

参数说明

参数名称 描述
context 当前内容的 Material 上下文
dialogTitle 弹窗标题,在顶部以大字体显示
displayDialogContent 是否显示弹窗内容
dialogContent 弹窗的中心内容
cancelBtnText 弹窗取消按钮的文字(左按钮)
acceptBtnText 弹窗确认按钮的文字(右按钮)
dialogRadius 弹窗边框圆角
barrierDismissible 是否可以通过外部点击关闭弹窗

示例代码

import 'package:bluetooth_enable/bluetooth_enable.dart';

Future<void> customEnableBT(BuildContext context) async {
  String dialogTitle = "嘿!请允许本应用使用蓝牙!";
  bool displayDialogContent = true;
  String dialogContent = "本应用需要蓝牙才能连接设备。";
  // 或者:
  // bool displayDialogContent = false;
  // String dialogContent = "";

  String cancelBtnText = "拒绝";
  String acceptBtnText = "同意";
  double dialogRadius = 10.0;
  bool barrierDismissible = true;

  BluetoothEnable.customBluetoothRequest(
          context,
          dialogTitle,
          displayDialogContent,
          dialogContent,
          cancelBtnText,
          acceptBtnText,
          dialogRadius,
          barrierDismissible)
      .then((result) {
    if (result == "true") {
      // 蓝牙已成功开启
    }
  });
}

完整示例代码

以下是一个完整的示例代码,展示如何使用 bluetooth_enable 插件请求蓝牙开关功能。

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

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      title: "测试蓝牙插件",
      home: _MyAppState(),
    );
  }
}

class _MyAppState extends StatelessWidget {
  // 请求开启蓝牙
  Future<void> enableBT() async {
    BluetoothEnable.enableBluetooth.then((value) {
      print("蓝牙状态: $value");
    });
  }

  // 自定义请求开启蓝牙
  Future<void> customEnableBT(BuildContext context) async {
    String dialogTitle = "嘿!请允许本应用使用蓝牙!";
    bool displayDialogContent = true;
    String dialogContent = "本应用需要蓝牙才能连接设备。";
    // 或者:
    // bool displayDialogContent = false;
    // String dialogContent = "";

    String cancelBtnText = "拒绝";
    String acceptBtnText = "同意";
    double dialogRadius = 10.0;
    bool barrierDismissible = true;

    BluetoothEnable.customBluetoothRequest(
            context,
            dialogTitle,
            displayDialogContent,
            dialogContent,
            cancelBtnText,
            acceptBtnText,
            dialogRadius,
            barrierDismissible)
        .then((result) {
      print("结果: $result");
    });
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text(
            '蓝牙启用插件示例',
          ),
          centerTitle: true,
        ),
        body: Center(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Text("按下按钮请求开启蓝牙"),
              SizedBox(height: 20.0),
              ElevatedButton(
                onPressed: () {
                  enableBT();
                },
                child: Text('请求开启蓝牙'),
              ),
              SizedBox(height: 10.0),
              ElevatedButton(
                onPressed: () {
                  customEnableBT(context);
                },
                child: Text('自定义请求开启蓝牙'),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

更多关于Flutter蓝牙启用管理插件bluetooth_enable的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter蓝牙启用管理插件bluetooth_enable的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


在Flutter中使用 bluetooth_enable 插件可以方便地管理和启用设备的蓝牙功能。这个插件允许你检查蓝牙状态,并在必要时请求用户启用蓝牙。以下是使用 bluetooth_enable 插件的详细步骤:

1. 添加依赖

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

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

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

2. 导入插件

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

import 'package:bluetooth_enable/bluetooth_enable.dart';

3. 检查蓝牙状态

你可以使用 BluetoothEnable.bluetoothState 来检查蓝牙的当前状态:

Future<void> checkBluetoothStatus() async {
  BluetoothState bluetoothState = await BluetoothEnable.bluetoothState;
  if (bluetoothState == BluetoothState.STATE_OFF) {
    print("Bluetooth is off");
  } else if (bluetoothState == BluetoothState.STATE_ON) {
    print("Bluetooth is on");
  } else {
    print("Bluetooth state is unknown");
  }
}

4. 启用蓝牙

如果蓝牙未启用,你可以使用 BluetoothEnable.enableBluetooth 来请求用户启用蓝牙:

Future<void> enableBluetooth() async {
  bool? result = await BluetoothEnable.enableBluetooth;
  if (result == true) {
    print("Bluetooth enabled successfully");
  } else {
    print("Failed to enable Bluetooth");
  }
}

5. 完整示例

以下是一个完整的示例,展示了如何检查蓝牙状态并启用蓝牙:

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

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

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

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

class _BluetoothEnablePageState extends State<BluetoothEnablePage> {
  String _bluetoothStatus = 'Unknown';

  Future<void> checkBluetoothStatus() async {
    BluetoothState bluetoothState = await BluetoothEnable.bluetoothState;
    setState(() {
      if (bluetoothState == BluetoothState.STATE_OFF) {
        _bluetoothStatus = "Bluetooth is off";
      } else if (bluetoothState == BluetoothState.STATE_ON) {
        _bluetoothStatus = "Bluetooth is on";
      } else {
        _bluetoothStatus = "Bluetooth state is unknown";
      }
    });
  }

  Future<void> enableBluetooth() async {
    bool? result = await BluetoothEnable.enableBluetooth;
    setState(() {
      if (result == true) {
        _bluetoothStatus = "Bluetooth enabled successfully";
      } else {
        _bluetoothStatus = "Failed to enable Bluetooth";
      }
    });
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Bluetooth Enable Example'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'Bluetooth Status:',
              style: TextStyle(fontSize: 20),
            ),
            Text(
              _bluetoothStatus,
              style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold),
            ),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: checkBluetoothStatus,
              child: Text('Check Bluetooth Status'),
            ),
            ElevatedButton(
              onPressed: enableBluetooth,
              child: Text('Enable Bluetooth'),
            ),
          ],
        ),
      ),
    );
  }
}
回到顶部