loading...

String Interpolation in Dart/Flutter

nombrekeff profile image Manolo Edge ・1 min read

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

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.

Posted on by:

nombrekeff profile

Manolo Edge

@nombrekeff

I don't know... I just code and they pay me!

Discussion

pic
Editor guide
 

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?

 

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.

 

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