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());
    }
  }
}

I want to send data to mqtt with the dart code above. But the "send" method is not working. After connecting to Mqtt, I want to send data with the help of another method. It gives me error as below.

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


Solution 1: nvoigt

You have not awaited the connect method before you sent something.

Since you did not post enough code, there is little more I can say.

I suggest you simplify your code (for example remove all the useless ? and ! since your client variable can never be null) and listen to your linter. connect should probably return a Future<void> otherwise awaiting it gets interesting.

If you need more detailed help, you will need to actually post the code that has the problems.