String Interpolation in Dart/Flutter

Keff - Mar 27 '20 - - Dev Community

String interpolation is the process of evaluating a string literal containing one or more placeholders, yielding a result in which the placeholders are replaced with their corresponding values

A little snippet to interpolate a Map in a string in Dart and Flutter using double curly braces syntax (can be easily changed).

String interpolate(String string, {Map<String, dynamic> params = const {}}) {
  var keys = params.keys;
  String result = string;
  for (var key in keys) {
    result = result.replaceAll('{{$key}}', params[key]);
  }

  return result;
}

// Usage
interpolate(
  'Hey {{name}}, {{greet}}', 
  params: {'name': 'Bob', 'greet': 'welcome back!'}
); // > 'Hey Bob, welcome back!'
Enter fullscreen mode Exit fullscreen mode

A bit of reading

I use this snippet for translating strings in a Flutter app and add interpolation to it, I've been searching and haven't been able to find how to do interpolation automatically with flutter translation (if you know any better way, please let me know :)).

I've made a gist containing the full approach to translating in Flutter with interpolation.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .