How can I convert string to utf8 in Dart?

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

}


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.


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