String Interpolation For Flutter

String Interpolation For Flutter

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.


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)


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);
Phill Wiggins

Phill Wiggins

💻 Mobile Apps Developer with experience in #Android, #Flutter and more. Tech geek and blogger, Gym rat & #Trance lover! 👔 Employment: Senior Mobile Software Engineer (Permanent) 🎂 Birthday: 15th May

3 thoughts on “String Interpolation For Flutter

Leave a Reply

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