【问题标题】:dart The connection must be in the Connected state in order to perform this operation.?dart 连接必须处于 Connected 状态才能执行此操作。
【发布时间】:2022-01-20 13:49:14
【问题描述】:
import 'package:mqtt_client/mqtt_client.dart';
import 'package:mqtt_client/mqtt_server_client.dart';

// ignore: camel_case_types
class mqttconnect {
  MqttServerClient? client =
      MqttServerClient.withPort('192.168.1.147', 'clientId-4ErbOoPajY', 1883);
  connect() async {
    client?.logging(on: true);
    client?.onConnected = onConnected;
    client?.onDisconnected = onDisconnected;

    try {
      await client?.connect();
    } catch (e) {
      print('Exception: $e');
      client!.disconnect();
    }
  }

  // connection succeeded
  void onConnected() {
    print('Connected');
  }

// unconnected
  void onDisconnected() {
    print('Disconnected');
  }

  void gonder() {
    try {
      client?.subscribe("ahmet", MqttQos.atLeastOnce);
      const pubTopic = 'ahmet';
      final builder = MqttClientPayloadBuilder();
      builder.addString('Hello MQTT1');
      client?.publishMessage(pubTopic, MqttQos.atLeastOnce, builder.payload!);
    } catch (e) {
      print(e.toString());
    }
  }
}

我想用上面的 dart 代码向 mqtt 发送数据。但是“发送”方法不起作用。连接到 Mqtt 后,我​​想借助另一种方法发送数据。它给了我如下错误。

flutter: mqtt-client::ConnectionException: The connection must be in the Connected state in order to perform this operation.

【问题讨论】:

    标签: flutter dart mqtt


    【解决方案1】:

    在您发送内容之前,您还没有awaited connect 方法。

    由于您没有发布足够多的代码,所以我能说的不多。

    我建议你简化你的代码(例如删除所有无用的?!,因为你的client 变量永远不能为空)并听你的linter。 connect 应该返回一个 Future<void> 否则等待它变得有趣。

    如果您需要更详细的帮助,您需要实际发布有问题的代码。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-14
      • 2014-03-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多