8

From time to time I need a non-breaking space in my Flutter Text widgets, e.g. a "Show more" link or a number with unit like "50 km/h".

The following code works fine but it looks overly complicated:

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

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

I'm curious if there is a shorter way to use an integer constant from the charcode package in my interpolated string?

RobDil
  • 4,036
  • 43
  • 52
  • It doesn't answer your question directly, but you can always extract that part to a variable so that the code will be more clear :) – Martin Oct 07 '20 at 14:03
  • Yes of course. I just thought I might be missing something essential when working with the integer constants. If it turns out that `String.fromCharCode` is the intended way to use them, you can post your comment as an answer in a few days and I will happily accept it. – RobDil Oct 07 '20 at 15:24

2 Answers2

17

The easy way to do it is using escape combination [\u{00A0}]:

Text('Hello\u{00A0}world');
Dmitry_Kovalov
  • 1,924
  • 1
  • 14
  • 11
  • Is there any way to use it with an integer variable like `$nbsp` from the charcode package? – RobDil Jul 30 '21 at 10:07
15

The best solution I have come up with is creating a String extension method.

// string_extension.dart

const int $nbsp = 0x00A0;

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

Usage example:

// import 'string_extension.dart';

Text('Hello World'.nonBreaking)
RobDil
  • 4,036
  • 43
  • 52