3

有时我需要在我的 Flutter Text 小部件中保留一个不间断的空间,例如“显示更多”链接或单位为“50 km/h”的数字。

以下代码工作正常,但看起来过于复杂:

const int $nbsp = 0x00A0; // from https://pub.dev/packages/charcode

print('Hello${String.fromCharCode($nbsp)}World'); // --> prints "Hello World", does not break
//          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ :/

我很好奇是否有更短的方法可以在我的插值字符串中使用charcode 包中的整数常量?

4

2 回答 2

6

最简单的方法是使用转义组合 [\u{00A0}]:

Text('Hello\u{00A0}world');
于 2021-07-28T14:51:00.480 回答
4

我想出的最佳解决方案是创建一个字符串扩展方法。

// string_extension.dart

const int $nbsp = 0x00A0;

extension StringExtension on String {
  String get nonBreaking => replaceAll(' ', String.fromCharCode($nbsp));
}

使用示例:

// import 'string_extension.dart';

Text('Hello World'.nonBreaking)
于 2021-04-11T20:10:05.993 回答