PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, October 22, 2022

[FIXED] How can I convert string to utf8 in Dart?

 October 22, 2022     aqueduct, converter, dart, sockets     No comments   

Issue

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


Solution

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



Answered By - Günter Zöchbauer
Answer Checked By - David Marino (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing