如何在Dart中将字符串转换为utf8? [英] How can I convert string to utf8 in Dart?
问题描述
我正在使用渡槽网络API框架来支持我的Flutter应用。在我的api后端中,我需要连接本地网络套接字服务。我的问题是我无法返回确切的字符串(在tr中)。 S o,如何在Dart中将字符串转换为utf8?
I am using aqueduct web api framework to support my flutter app. In my api backend I need to connect local network socket services. My problem is that I can't return the exact string (in tr). So, How can I convert string to utf8 in Dart?
示例:
@httpGet
Future<Response> getLogin() async {
Socket.connect('192.168.1.22’, 1024).then((socket) async {
socket.listen((data) {
// Expected return is: 1:_:2:_:175997:_:NİYAZİ TOROS
print(new String.fromCharCodes(data).trim());
xResult = new String.fromCharCodes(data).trim();
print("xResult: $xResult");
}, onDone: () {
print("Done");
socket.destroy();
});
socket.write('Q101:_:49785:_:x\r\n');
});
return new Response.ok(xResult);
}
返回值不是TR-tr语言格式。
The return is not in TR-tr language format.
返回文本如下:
1::2::175997:_:NÝYAZÝTOROS
Return text looks like: 1::2::175997:_:NÝYAZÝ TOROS
正确的必须是:
1::2::175997:_:NİYAZİTOROS
Correct must be: 1::2::175997:_:NİYAZİ TOROS
更新:
-
xResult = new String.fromCharCodes (data).trim();
-
print(xResult);
-
responseBody = xResult.transform(utf8.decoder);
-
print(responseBody) ;
xResult = new String.fromCharCodes(data).trim();
print(xResult);
responseBody = xResult.transform(utf8.decoder);
print(responseBody);
我可以打印 xResult
但尝试转换为UTF8后无法打印 responseBody
I can print the xResult
but cannot print the responseBody
after trying convert to UTF8
推荐答案
import 'dart:convert' show utf8;
var encoded = utf8.encode('Lorem ipsum dolor sit amet, consetetur...');
var decoded = utf8.decode(encoded);
另请参见 https://api.dartlang.org/stable/1.24.3/dart-convert/UTF8-constant.html
还有用于流的编码器和解码器
There are also encoder and decoder to be used with streams
File.openRead().transform(utf8.decoder).
另请参见 https://www.dartlang.org/articles/libraries/converters-and-codecs#converter
这篇关于如何在Dart中将字符串转换为utf8?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!