相关文章推荐
睡不着的橡皮擦  ·  IllegalArgumentExcepti ...·  2 周前    · 
豪气的红豆  ·  fgbg = ...·  5 月前    · 
淡定的匕首  ·  mongoose之findOneAndUpd ...·  1 年前    · 
耍酷的西红柿  ·  webpack-dev-server的pro ...·  1 年前    · 
非常酷的葡萄  ·  Mysql No operations ...·  1 年前    · 
Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

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). S o, How can I convert string to utf8 in Dart?

Example:

@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);

The return is not in TR-tr language format.

Return text looks like:

**1:_:2:_:175997:_:NÝYAZÝ TOROS**

Correct must be:

**1:_:2:_:175997:_:NİYAZİ TOROS**

UPDATE:

  • xResult = new String.fromCharCodes(data).trim();
  • print(xResult);
  • responseBody = xResult.transform(utf8.decoder);
  • print(responseBody);
  • I can print the xResult but cannot print the responseBody after trying convert to UTF8

    in the 4. step is not printing. means responseBody is null, meaning utf8.decoder didn't do anything – user9239214 Jun 29, 2018 at 12:56 Ok. I cenge it to responseBody = utf8.decode(xResult); and still can't print responseBody – user9239214 Jun 29, 2018 at 13:19
    import 'dart:convert' show utf8;
    var encoded = utf8.encode('Lorem ipsum dolor sit amet, consetetur...');
    var decoded = utf8.decode(encoded);
    

    See also 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).
    

    See also https://www.dartlang.org/articles/libraries/converters-and-codecs#converter

    List<int> fileBytes = await file.readAsBytes(); Then used the utf8.decode(fileBytes). works as per the requirement. :) – Rakesh Verma Dec 22, 2022 at 13:33
     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();
    

    This is not the solution for your specific case but relative to the title.

    If your string is a Uri, use:

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

    Android string Uri is an example use case, here is a demo before and after using Uri.decodeFull():

    To/from Uint8List

    //Uint8List to String
    Uint8List bytes = utf8.encode(String s) as Uint8List;
    //String to Uint8List
    String s = utf8.decode(bytes.toList());
    Uint8List myUint8List = utf8.encode('yourTextHere') as Uint8List;
    // List<int> to Uint8List:
    Uint8List myUint8List = Uint8List.fromList(byteIntList);
            

    Thanks for contributing an answer to Stack Overflow!

    • Please be sure to answer the question. Provide details and share your research!

    But avoid

    • Asking for help, clarification, or responding to other answers.
    • Making statements based on opinion; back them up with references or personal experience.

    To learn more, see our tips on writing great answers.