如何在Dart中将string转换为utf8?

6g8kf2rb  于 2022-12-15  发布在  其他
关注(0)|答案(6)|浏览(452)

我正在使用aqueduct web API框架来支持我的flutter应用程序。在我的api后端,我需要连接本地网络套接字服务。我的问题是,我不能返回准确的字符串(在tr中)。So,我如何在Dart中将字符串转换为utf8?

示例:

@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语言格式。
返回文本如下所示:1::2::175997:_:尼亚齐·托罗斯
正确的必须是:1::2::175997:_:尼牙孜·托罗斯
更新:

  1. xResult = new String.fromCharCodes(data).trim();
  2. print(xResult);
  3. responseBody = xResult.transform(utf8.decoder);
  4. print(responseBody);
    我可以打印xResult,但在尝试转换为UTF8后无法打印responseBody
iswrvxsc

iswrvxsc1#

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
还有编码器和解码器用于流

File.openRead().transform(utf8.decoder).

另请参见https://www.dartlang.org/articles/libraries/converters-and-codecs#converter

u4vypkhs

u4vypkhs2#

utf8.decode(stringData.runes.toList()),

这可以用于获取flutter中的UTF-8。这里stringData字符串将包含具有UTF-8内容的必要数据。

ovfsdjhp

ovfsdjhp3#

尝试使用utf-8转换使用此代码

final message =  utf8.decode(data);

而不是这个

final message = String.fromCharCodes(data);

导入

import 'dart:convert';

void handleConnection(Socket client) {
print('Connection from'
    ' ${client.remoteAddress.address}:${client.remotePort}');

// listen for events from the client
client.listen(
  // handle data from the client
  (Uint8List data) async {
    await Future.delayed(Duration(seconds: 1));
    final message =  utf8.decode(data);
    // final message = String.fromCharCodes(data);
    int length = messageWidgets.length;
    Widget padding2 = Padding(
      padding: const EdgeInsets.all(8.0),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.start,
        children: [
          Expanded(
            flex: 1,
            child: GestureDetector(
                onLongPress: () {
                  _copy(message);
                },
                onDoubleTap: () {
                  setState(() {
                    messageWidgets.removeAt(length);
                  });
                },
                child: Container(
                  padding: EdgeInsets.all(8.0),
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(10),
                    color: Color(0xDD44871F),
                  ),
                  child: Stack(
                    children: <Widget>[
                      Column(
                        // direction: Axis.vertical,
                        children: [
                          Text("${client.remoteAddress.host}::-",
                              style: TextStyle(color: Colors.black87)),
                          Text("${message}",
                              style: TextStyle(color: Colors.black87)),
                        ],
                      )
                    ],
                  ),
                )),
          ),
          Expanded(
            flex: 1,
            child: Container(),
          ),
        ],
      ),
    );
    setState(() {
      messageWidgets.add(padding2);
    });
  },

  // handle errors
  onError: (error) {
    print(error);
    setMwidget(error);
    client.close();
  },

  // handle the client closing the connection
  onDone: () {
    print('Client left');
    client.close();
  },
);

}

dluptydi

dluptydi4#

这不是针对您的特定情况的解决方案,而是相对于标题的解决方案。
如果字符串是URI,请用途:

final decodedUri = Uri.decodeFull('your-string-uri')

Android字符串Uri是一个示例用例,下面是使用Uri.decodeFull()前后的演示:

4zcjmb1e

4zcjmb1e5#

至/自Uint 8列表

//Uint8List to String
Uint8List bytes = utf8.encode(String s) as Uint8List;

//String to Uint8List
String s = utf8.decode(bytes.toList());
t5zmwmid

t5zmwmid6#

有用的相关转换:

import 'dart:convert';
import 'dart:typed_data';

// Text to byte:
List<int> byteIntList = utf8.encode('yourTextHere');

// Text to Uint8List:
Uint8List myUint8List = utf8.encode('yourTextHere') as Uint8List;

// List<int> to Uint8List:
Uint8List myUint8List = Uint8List.fromList(byteIntList);

相关问题