How can I convert string to utf8 in Dart?
Asked Answered
C

7

28

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?

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:

  1. xResult = new String.fromCharCodes(data).trim();
  2. print(xResult);
  3. responseBody = xResult.transform(utf8.decoder);
  4. print(responseBody);

I can print the xResult but cannot print the responseBody after trying convert to UTF8

Canova answered 29/6, 2018 at 12:12 Comment(15)
What does "cannot print" mean?Schwartz
in the 4. step is not printing. means responseBody is null, meaning utf8.decoder didn't do anythingCanova
Why did you use transform? You are not using a stream.Schwartz
I don't know how to do it. I get confusedCanova
Ok. I cenge it to responseBody = utf8.decode(xResult); and still can't print responseBodyCanova
Hard to tell without more concrete information. Perhaps you need print(utf8.decode(data));Schwartz
it prints the first one like print("xResult: $xResult"); but doesnt print second one. print(utf8.decode(data)); than I put only print(utf8.decode(data)); and still didn't print anything. Only prints this line; xResult = new String.fromCharCodes(data).trim(); print("xResult: $xResult");Canova
Then the problem is probably already in data.Schwartz
I can print as 1::2::175997:_:NÝYAZÝ TOROS. But all the character Ý must be İCanova
and if I say print(data) I get this: [49, 58, 95, 58, 50, 58, 95, 58, 54, 50, 51, 52, 51, 48, 58, 95, 58, 78, 221, 89, 65, 90, 221, 32, 84, 79, 82, 79, 83, 13, 10]Canova
Your data seems to be encoded as Latin-5 (en.wikipedia.org/wiki/ISO/IEC_8859-5). Dart does not have a built-in decoder for Latin-5 (only Latin-1 because that is a direct subset of Unicode code points so conversion is trivial). You will have to manually convert between Latin-5 and Unicode code points. When that is done, you can create a String using Strong.fromCharCodes.Luzluzader
Thanks Irn, I will try thatCanova
My bad, I was thinking of Windows Latin 5, not ISO Latin 5. Turkish is probably ISO Latin 9 instead.Luzluzader
Thanks Irn, I use simple switch statement to replace the character. I know the differences between Latin 1 and 9.Canova
.runes.toList() for a String #61497173Photolysis
G
54
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

Geof answered 29/6, 2018 at 12:19 Comment(2)
File.openRead().transform(utf8.encoder) is give an errorBathymetry
List<int> fileBytes = await file.readAsBytes(); Then used the utf8.decode(fileBytes). works as per the requirement. :)Orchardman
P
23
utf8.decode(stringData.runes.toList()),

This could be used to get the UTF-8 in flutter. here the stringData string will contain the necessary data with UTF-8 content.

Parameter answered 7/2, 2020 at 9:10 Comment(0)
T
9
import 'dart:convert';

const originalString = 'En Español'; 
final decodedString = utf8.decode(originalString.codeUnits);
print(decodedString); // prints 'En Español'

Just an alternative in case you have to convert strings.

Trautman answered 25/8, 2023 at 12:39 Comment(1)
originalString.codeUnits are UTF-16 while decode accept ute-8 it will fail on another languagesBefore
U
2

Try to use utf-8 convertion Use this code

 final message =  utf8.decode(data);

Instead of this

final message = String.fromCharCodes(data);

import

 import 'dart:convert';

enter image description here

 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();
  },
);

}

Unipod answered 3/10, 2021 at 8:12 Comment(0)
R
1

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():

before decoding

after decoding

Remex answered 27/8, 2022 at 15:11 Comment(0)
E
0

To/from Uint8List

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

//String to Uint8List
String s = utf8.decode(bytes.toList());
Engleman answered 9/9, 2022 at 1:37 Comment(0)
B
0

Useful related convertions:

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);
Bushweller answered 15/12, 2022 at 4:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.