Search code examples
flutterdartmqtt

How to Send data as JSON over to MQTT broker in flutter


    return RaisedButton(
      color: Colors.green,
      disabledColor: Colors.grey,
      textColor: Colors.white,
      disabledTextColor:Colors.black38 ,
      child: Text("Break"),
      onPressed: state == MQTTAppConnectionState.connectedSubscribed
          ? () {
        setState(() {
          value = 0;
          action = jsonData;
        });
        publishMessage(action);
      }
          : null, //
    );
  }

I have multiple buttons in my app that passes different message  to mqtt client


I want to pass  different json data to mqtt client for each button 


sample json data for single button 

{ "Motor":"BLDC motor", "Acc": 70, "F/R": "Forward", "Break":"False", "Key":"True" }

help me to pass single json data to mqtt client when the button is pressed


Solution

  • Pass the values in the publish method and make this changes there it will work

    return RaisedButton(
      color: Colors.green,
      disabledColor: Colors.grey,
      textColor: Colors.white,
      disabledTextColor:Colors.black38 ,
      child: Text("Break"),
      onPressed: state == MQTTAppConnectionState.connectedSubscribed
          ? () {
        setState(() {
          break1 = "True";
          value = 0;
        });
        publish(break1);
      }
          : null,//
    );
    
    void publish(String break1) {
    final MqttClientPayloadBuilder builder = MqttClientPayloadBuilder();
    builder.addString(
      json.encode(
        {
          "break": "$break1",
        }
      )
    );
    _client!.publishMessage(_topic, MqttQos.exactlyOnce, builder.payload!);}