简体   繁体   English

如何尊重列表中的回车(CR)<int> 在飞镖/颤振中进入字符串</int>

[英]How to respect carriage return (CR) from List<int> into String in dart/flutter

I'm trying to convert List into String and show it in Text widget in flutter but it's not working as expected.我正在尝试将 List 转换为 String 并在 flutter 的 Text 小部件中显示它,但它没有按预期工作。 Snippet below:片段如下:

import 'dart:convert' show utf8;

List<int> val = [49, 46, 13, 104, 101, 108, 108, 111];
final decoded = utf8.decode(val);


....

Container(
    child: Text(decoded)
)

The text is showing:文字显示:

  1. hello你好

it should be:它应该是:

1. 1.
hello你好

Why it does not respect 13 (equivalent to carriage return)?为什么它不尊重13(相当于回车)?

Any help is appreciated.任何帮助表示赞赏。

Thanks!谢谢!

Try use LineSplitter to split the String into a list of lines and then combine the lines again using a StringBuffer :尝试使用LineSplitterString拆分为行列表,然后使用StringBuffer再次组合行:

import 'dart:convert' show utf8, LineSplitter;

void main() {
  final val = [49, 46, 13, 104, 101, 108, 108, 111];
  final lines = const LineSplitter().convert(utf8.decode(val));
  print(lines); // [1., hello]

  final message = lines
      .fold<StringBuffer>(
          StringBuffer(), (buffer, line) => buffer..writeln(line))
      .toString();
  print(message);
  // 1.
  // hello
}

This will ensure you are using the running platform supported line endings.这将确保您使用运行平台支持的行尾。

If it works it can be shorten down to:如果它有效,它可以缩短为:

import 'dart:convert' show utf8, LineSplitter;

void main() {
  List<int> val = [49, 46, 13, 104, 101, 108, 108, 111];

  final decoded = utf8.decode(val);
  print(decoded);

  final fixed = fixNewLines(decoded);
  print(fixed);
}

String fixNewLines(String text) => const LineSplitter()
    .convert(text)
    .fold<StringBuffer>(StringBuffer(), (buffer, line) => buffer..writeln(line))
    .toString();

For some reasons, Flutter looks for LF for line break and ignore CR.由于某些原因,Flutter 寻找 LF 换行并忽略 CR。 If you replace 13 (CR) by 10 (LF) it will works.如果将 13 (CR) 替换为 10 (LF) 它将起作用。

I don't know if this is a bug or it is platform dependent (tested on Android).我不知道这是一个错误还是依赖于平台(在 Android 上测试)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM