DEV Community


Posted on

String Interpolation in Dart/Flutter

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
  '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.

Top comments (3)

incrypto32 profile image

Liked the content :).
A little off-topic but how did u do that table of contents sort of table (My snippets(6 Part series) ).
Is it possible in markdown or is it something else?

nombrekeff profile image

Glad you liked it!

That's added automatically when you add multiple posts to the same series, can be found under the 3 dots when editing a post, there you will see Series Name.

incrypto32 profile image

Thanks man :)
Iam a Little new here
Iam looking forward to write some content here in the future.