Flutter串口通信插件serialport_plus的使用

Flutter串口通信插件serialport_plus的使用

serialport_plus 是一个集成 Android-SerialPort-API 的 Flutter 插件。此插件仅适用于已root的Android设备。

使用方法

列出设备
List devices = await SerialportFlutter.listDevices();
列出设备路径
List devices = await SerialportFlutter.listDevicesPath();
打开/关闭设备
bool openResult = await SerialportFlutter.open('/your/device/path', baudrate, dataBits, parity, stopBits);
bool closeResult = await SerialportFlutter.close();
向设备写入数据
SerialportFlutter.write(Uint8List.fromList("Write some data".codeUnits));

完整示例Demo

以下是一个完整的示例代码,展示了如何使用 serialport_plus 插件来列出设备并打开设备进行数据通信。

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

import 'package:flutter/services.dart';
import 'package:serialport_plus/serialport_plus.dart';

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

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

  [@override](/user/override)
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  List _devices = [];
  final _serialportFlutterPlugin = SerialportPlus();

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

  [@override](/user/override)
  void dispose() async {
    await _serialportFlutterPlugin.close();
    super.dispose();
  }

  Future<void> getDevices() async {
    List? devices;
    try {
      devices = (await _serialportFlutterPlugin.getAllDevicesPath());
    } on PlatformException {
      devices = [];
    }
    if (!mounted) return;

    setState(() {
      _devices = devices!;
    });
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('串口通信示例应用'),
        ),
        body: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Expanded(
              child: Scrollbar(
                child: ListView(
                  children: [
                    for (final device in _devices)
                      Builder(
                        builder: (context) {
                          return Text(device);
                        },
                      ),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

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

1 回复

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


当然,以下是一个关于如何在Flutter应用中使用serialport_plus插件来实现串口通信的示例代码。这个示例将涵盖基本的串口打开、读取和写入操作。

首先,确保你已经在你的pubspec.yaml文件中添加了serialport_plus依赖:

dependencies:
  flutter:
    sdk: flutter
  serialport_plus: ^x.y.z  # 替换为最新版本号

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

接下来,在你的Flutter项目中创建一个服务来管理串口通信。这里是一个简单的示例:

// serial_service.dart
import 'dart:typed_data';
import 'package:flutter/services.dart';
import 'package:serialport_plus/serialport_plus.dart';

class SerialService {
  late SerialPort _serialPort;
  late MethodChannel _channel;

  SerialService() {
    _channel = MethodChannel('com.example.flutter_serial_communication');
  }

  Future<void> openPort(String portName, int baudRate) async {
    try {
      _serialPort = await SerialPort.fromPath(portName, baudRate);
      _serialPort.inputStream.listen((Uint8List data) {
        // 处理接收到的数据
        String receivedData = String.fromCharCodes(data);
        print("Received: $receivedData");
        _channel.invokeMethod('onDataReceived', receivedData);
      });
      print("Port opened successfully.");
    } catch (e) {
      print("Error opening port: $e");
      _channel.invokeMethod('onError', e.toString());
    }
  }

  Future<void> writeData(String data) async {
    try {
      if (_serialPort.isOpen) {
        _serialPort.write(data.codeUnits);
        print("Data written: $data");
      } else {
        print("Port is not open.");
      }
    } catch (e) {
      print("Error writing data: $e");
      _channel.invokeMethod('onError', e.toString());
    }
  }

  Future<void> closePort() async {
    try {
      if (_serialPort.isOpen) {
        await _serialPort.close();
        print("Port closed.");
      }
    } catch (e) {
      print("Error closing port: $e");
      _channel.invokeMethod('onError', e.toString());
    }
  }
}

然后,在你的Flutter应用的Dart文件中(比如main.dart),你可以使用这个服务来与串口进行交互:

// main.dart
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'serial_service.dart';

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

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  late SerialService _serialService;
  final MethodChannel _channel = MethodChannel('com.example.flutter_serial_communication');
  String _portName = "/dev/ttyUSB0";  // 根据你的设备修改
  int _baudRate = 9600;
  String _receivedData = "";
  TextEditingController _controller = TextEditingController();

  @override
  void initState() {
    super.initState();
    _serialService = SerialService();
    _channel.setMethodCallHandler((MethodCall call) async {
      if (call.method == 'onDataReceived') {
        setState(() {
          _receivedData += call.arguments;
        });
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Flutter Serial Communication'),
        ),
        body: Padding(
          padding: const EdgeInsets.all(16.0),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              Text('Received Data:', style: TextStyle(fontSize: 18)),
              Text(_receivedData, style: TextStyle(fontSize: 16)),
              SizedBox(height: 20),
              Text('Send Data:', style: TextStyle(fontSize: 18)),
              TextField(
                controller: _controller,
                decoration: InputDecoration(border: OutlineInputBorder()),
              ),
              SizedBox(height: 10),
              Row(
                children: <Widget>[
                  ElevatedButton(
                    onPressed: () async {
                      await _serialService.openPort(_portName, _baudRate);
                    },
                    child: Text('Open Port'),
                  ),
                  SizedBox(width: 10),
                  ElevatedButton(
                    onPressed: () async {
                      await _serialService.writeData(_controller.text);
                      _controller.clear();
                    },
                    child: Text('Send Data'),
                  ),
                  SizedBox(width: 10),
                  ElevatedButton(
                    onPressed: () async {
                      await _serialService.closePort();
                    },
                    child: Text('Close Port'),
                  ),
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }
}

这个示例展示了如何使用serialport_plus插件在Flutter应用中打开串口、读取数据和写入数据。请注意,根据你的设备和平台,串口路径(_portName)可能需要调整。同时,确保你的应用有适当的权限来访问串口设备。在Android上,你可能需要在AndroidManifest.xml中声明权限,而在iOS上,你可能需要配置Info.plist

回到顶部