I have a JSON like message like this:
static getHiMsg(String token, String sender) {
var msg = {
"token": token,
"user_addr": sender,
"ua": "dart/fluter-v0.0.1",
"device": "Phone",
"location": "Hunan"
};
var outMsg = {
"msg_type": "hi",
"payload": msg
};
return outMsg;
}
and I wanna send this message to websocket server which only deal with json request, if a plain text or wrong format json, it will refuse connection.
Here is what am doing:
void _sayHi() async {
_token = await _prefs.getToken();
_userAddr = await _prefs.getUserAddr();
var hi = getHiMsg(_token, _userAddr);
print(hi);
channel.sink.add(hi);
}
channel is just IOWebSocketChannel.connect(wsUrl) Here my server just can not get the right JSON format request, actually this is the right logic in Python:
def hi_msg(token, addr):
# change this to one account token and user_addr
msg = {
"token": token,
"user_addr": addr,
"ua": "py/macos",
"device": "mac",
"location": "Hunan"
}
out_msg = {
"msg_type": "hi",
"payload": msg
}
msg_str = json.dumps(out_msg)
b = bytes(msg_str, 'utf-8')
return b
How to achieve this in Dart and Flutter? I am not quite familiar with Dart bytes operation.
You can get a JSON string in Dart
import 'dart:convert';
...
var jsonString = json.encode(data);
and get bytes of the string using
var bytes = jsonString.codeUnits;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With