25

I'm creating a Redis client and would like to create a byte array for sending to the Redis server. To issue commands to the server, I need to convert Dart's UTF-8 strings into a bytes which can be written to a socket.

How can I do this?

Mark B
  • 2,870
  • 3
  • 20
  • 18

3 Answers3

51

For Dart >1.0 this is now done with the convert library.

import 'dart:convert';
List<int> bytes = utf8.encode("Some data");
print(bytes) //[115, 111, 109, 101, 32, 100, 97, 116, 97]
MahMoos
  • 1,014
  • 9
  • 16
Delaney
  • 1,039
  • 1
  • 9
  • 15
  • 3
    UTF8 is deprecated sind Dart 2. But it was just renamed to utf8: List bytes = utf8.encode("Some data"); – Minsky Apr 16 '18 at 10:50
  • I encoded the some Chinese character and put it into a pdf file and print it from printer. it only shows numbers. May I know how to print the Chinese character? var encoded = utf8.encode("檯號: 1"); g.drawString(ttf, 20.0, '$encoded', 10.0 * PDFPageFormat.MM, top - 10.0 * PDFPageFormat.MM); – GPH Oct 21 '18 at 15:47
7

You need to import dart:utf and use its encodeUtf8 function. There is actually a existing redis client for Dart here which makes use of these functions.

Lars Tackmann
  • 20,275
  • 13
  • 66
  • 83
  • Thanks Lars, that's very helpful. I'll try that out with the socket connection and see how it goes. – Mark B May 02 '12 at 02:14
-1

for images, they might be base64 encoded refer to this

https://stackoverflow.com/a/65146858/4412553

Image.memory(base64.decode('base64EncodedImageString')),
A.Mushate
  • 395
  • 3
  • 7