DEV Community

Keff
Keff

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

Top comments (3)

Collapse
 
incrypto32 profile image
Krishnanand

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?

Collapse
 
nombrekeff profile image
Keff

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.

Collapse
 
incrypto32 profile image
Krishnanand

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