Flutter蓝牙通信插件rtk_bluetooth的使用

Flutter蓝牙通信插件rtk_bluetooth的使用

rtk_bluetooth 插件用于经典蓝牙连接支持NMEA语句输出的RTK设备,例如合众思壮、中海达等厂商的产品。

使用方法

以下是一个完整的示例代码,展示如何在Flutter应用中使用 rtk_bluetooth 插件进行蓝牙通信。

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

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

class App extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      routes: {
        "/": (context) => const MyApp(),
      },
    );
  }
}

class MyApp extends StatefulWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  List<String> list = [];
  bool isConnected = false;

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('经典蓝牙'),
          actions: [
            TextButton(
                onPressed: () {
                  if (isConnected) {
                    RtkBluetooth.close(callBack: (data) {
                      setState(() {
                        isConnected = false;
                      });
                    });
                  } else {
                    initBlueTooth();
                  }
                },
                child: Text(!isConnected ? "连接" : "断开",
                    style: const TextStyle(
                      color: Colors.white,
                    ))),
            TextButton(
                onPressed: () {
                  showAboutDialog(
                      context: context,
                      children: [SelectableText(list.join("|"))]);
                },
                child: const Text("导出",
                    style: TextStyle(
                      color: Colors.white,
                    )))
          ],
        ),
        body: Center(
          child: ListView(
            children: list
                .map((e) => ListTile(
                      title: Text(e),
                    ))
                .toList(),
          ),
        ),
      ),
    );
  }

  initBlueTooth() async {
    var nema = NmeaUitls(locationCallBack: (location) {
      print(location);
    });
    List<DeviceInfo> devices = await RtkBluetooth.getBondDevices;
    // 直接使用第一个已配对的设备
    RtkBluetooth.connect(
        callBack: (info) {
          print(info);
          setState(() {
            isConnected = true;
          });
        },
        address: devices.first.address!);
    RtkBluetooth.onNmeaChange.listen((event) {
      print(event);
      list.insert(0, event);

      setState(() {});
      nema.handleNmea(event);
    });
  }
}

代码说明

  1. 导入必要的包

    import 'package:flutter/material.dart';
    import 'package:rtk_bluetooth/rtk_bluetooth.dart';
    
  2. 初始化应用

    void main() {
      runApp(App());
    }
    
  3. 定义主应用类

    class App extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          routes: {
            "/": (context) => const MyApp(),
          },
        );
      }
    }
    
  4. 定义状态管理类

    class MyApp extends StatefulWidget {
      const MyApp({Key? key}) : super(key: key);
    
      @override
      State<MyApp> createState() => _MyAppState();
    }
    
    class _MyAppState extends State<MyApp> {
      List<String> list = [];
      bool isConnected = false;
    
      @override
      void initState() {
        super.initState();
      }
    
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          home: Scaffold(
            appBar: AppBar(
              title: const Text('经典蓝牙'),
              actions: [
                TextButton(
                    onPressed: () {
                      if (isConnected) {
                        RtkBluetooth.close(callBack: (data) {
                          setState(() {
                            isConnected = false;
                          });
                        });
                      } else {
                        initBlueTooth();
                      }
                    },
                    child: Text(!isConnected ? "连接" : "断开",
                        style: const TextStyle(
                          color: Colors.white,
                        ))),
                TextButton(
                    onPressed: () {
                      showAboutDialog(
                          context: context,
                          children: [SelectableText(list.join("|"))]);
                    },
                    child: const Text("导出",
                        style: TextStyle(
                          color: Colors.white,
                        )))
              ],
            ),
            body: Center(
              child: ListView(
                children: list
                    .map((e) => ListTile(
                          title: Text(e),
                        ))
                    .toList(),
              ),
            ),
          ),
        );
      }
    }
    
  5. 初始化蓝牙连接

    initBlueTooth() async {
      var nema = NmeaUitls(locationCallBack: (location) {
        print(location);
      });
      List<DeviceInfo> devices = await RtkBluetooth.getBondDevices;
      // 直接使用第一个已配对的设备
      RtkBluetooth.connect(
          callBack: (info) {
            print(info);
            setState(() {
              isConnected = true;
            });
          },
          address: devices.first.address!);
      RtkBluetooth.onNmeaChange.listen((event) {
        print(event);
        list.insert(0, event);
    
        setState(() {});
        nema.handleNmea(event);
      });
    }
    

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

1 回复

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


rtk_bluetooth 是一个用于Flutter的蓝牙通信插件,它提供了与蓝牙设备进行通信的功能。以下是如何使用 rtk_bluetooth 插件的基本步骤:

1. 添加依赖

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

dependencies:
  flutter:
    sdk: flutter
  rtk_bluetooth: ^1.0.0  # 请检查最新版本

然后运行 flutter pub get 来获取依赖。

2. 导入插件

在你的Dart文件中导入 rtk_bluetooth 插件。

import 'package:rtk_bluetooth/rtk_bluetooth.dart';

3. 初始化蓝牙

在使用蓝牙功能之前,你需要初始化蓝牙适配器。

RtkBluetooth bluetooth = RtkBluetooth.instance;

Future<void> initBluetooth() async {
  bool isAvailable = await bluetooth.isAvailable();
  if (isAvailable) {
    print("Bluetooth is available");
  } else {
    print("Bluetooth is not available");
  }
}

4. 扫描设备

你可以使用 startScan 方法来扫描附近的蓝牙设备。

Future<void> scanDevices() async {
  bluetooth.startScan().listen((device) {
    print("Found device: ${device.name}, ${device.address}");
  });
}

5. 连接设备

扫描到设备后,你可以使用 connect 方法来连接设备。

Future<void> connectToDevice(String deviceAddress) async {
  await bluetooth.connect(deviceAddress);
  print("Connected to device: $deviceAddress");
}

6. 发送和接收数据

连接成功后,你可以使用 write 方法发送数据,并使用 onDataReceived 监听数据接收。

Future<void> sendData(String data) async {
  await bluetooth.write(data);
  print("Data sent: $data");
}

void listenForData() {
  bluetooth.onDataReceived.listen((data) {
    print("Data received: $data");
  });
}

7. 断开连接

当你不再需要与设备通信时,可以断开连接。

Future<void> disconnectDevice() async {
  await bluetooth.disconnect();
  print("Disconnected from device");
}

8. 处理权限

在Android和iOS上,蓝牙通信可能需要特定的权限。请确保在 AndroidManifest.xmlInfo.plist 中添加必要的权限。

Android

AndroidManifest.xml 中添加以下权限:

<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

iOS

Info.plist 中添加以下键值对:

<key>NSBluetoothAlwaysUsageDescription</key>
<string>We need access to Bluetooth to connect to devices.</string>
<key>NSBluetoothPeripheralUsageDescription</key>
<string>We need access to Bluetooth to connect to devices.</string>

9. 处理错误

在实际使用中,你可能会遇到各种错误,例如连接失败或权限被拒绝。你可以使用 try-catch 块来处理这些错误。

Future<void> connectToDevice(String deviceAddress) async {
  try {
    await bluetooth.connect(deviceAddress);
    print("Connected to device: $deviceAddress");
  } catch (e) {
    print("Failed to connect: $e");
  }
}

10. 完整示例

以下是一个完整的示例,展示了如何使用 rtk_bluetooth 插件进行蓝牙通信。

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

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

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

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

class _BluetoothScreenState extends State<BluetoothScreen> {
  RtkBluetooth bluetooth = RtkBluetooth.instance;
  String deviceAddress = "";

  [@override](/user/override)
  void initState() {
    super.initState();
    initBluetooth();
  }

  Future<void> initBluetooth() async {
    bool isAvailable = await bluetooth.isAvailable();
    if (isAvailable) {
      print("Bluetooth is available");
    } else {
      print("Bluetooth is not available");
    }
  }

  Future<void> scanDevices() async {
    bluetooth.startScan().listen((device) {
      print("Found device: ${device.name}, ${device.address}");
      setState(() {
        deviceAddress = device.address;
      });
    });
  }

  Future<void> connectToDevice() async {
    try {
      await bluetooth.connect(deviceAddress);
      print("Connected to device: $deviceAddress");
    } catch (e) {
      print("Failed to connect: $e");
    }
  }

  Future<void> sendData(String data) async {
    await bluetooth.write(data);
    print("Data sent: $data");
  }

  void listenForData() {
    bluetooth.onDataReceived.listen((data) {
      print("Data received: $data");
    });
  }

  Future<void> disconnectDevice() async {
    await bluetooth.disconnect();
    print("Disconnected from device");
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Bluetooth Communication"),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            ElevatedButton(
              onPressed: scanDevices,
              child: Text("Scan Devices"),
            ),
            ElevatedButton(
              onPressed: connectToDevice,
              child: Text("Connect to Device"),
            ),
            ElevatedButton(
              onPressed: () => sendData("Hello Bluetooth"),
              child: Text("Send Data"),
            ),
            ElevatedButton(
              onPressed: disconnectDevice,
              child: Text("Disconnect"),
            ),
          ],
        ),
      ),
    );
  }
}
回到顶部