String Interpolation

If you want String interpolation similar to Android (Today is %1$ and tomorrow is %2$), you can create a top level function, or an extension that can do something similar. In this instance I keep it similar to Android strings as I’m currently porting an Android app (Interpolation formatting starts with 1 rather than 0)

Top Level Function

String interpolate(String string, List<String> params) {

  String result = string;
  for (int i = 1; i < params.length + 1; i++) {
    result = result.replaceAll('%${i}\$', params[i-1]);
  }

  return result;
}

You can then call interpolate(STRING_TO_INTERPOLATE, LIST_OF_STRINGS) and you string would be interpolated.

Extensions

You can create an extension function that does something similarish to Android String.format()

extension StringExtension on String {
    String format(List<String> params) => interpolate(this, params);
}

This would then allow you to call text.format(placeHolders)

Testing

Couple of tests for proof of concent:-

test('String.format extension works', () {
    // Given
    const String text = 'Today is %1\$ and tomorrow is %2\$';
    final List<String> placeHolders = List<String>()..add('Monday')..add('Tuesday');
    const String expected = 'Today is Monday and tomorrow is Tuesday';

    // When
    final String actual = text.format(placeHolders);

    // Then
    expect(actual, expected);
  });
Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *