Search code examples
flutterstring-interpolationcharacter-codes

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?


Solution

  • 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)