RobDil
RobDil

Reputation: 4544

Non-breaking space in Flutter string interpolation

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?

Upvotes: 9

Views: 6368

Answers (2)

Dmitry_Kovalov
Dmitry_Kovalov

Reputation: 2172

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

Text('Hello\u{00A0}world');

Upvotes: 24

RobDil
RobDil

Reputation: 4544

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)

Upvotes: 21

Related Questions