How to Format an Interploated String In Flutter ?
Earlier we have been through How to find Difference Between Two Dates In Flutter. So this time we will try something new like How to Format an Interpolated String In Flutter.
Let move ahead with it.
How to Format an Interpolated String In Flutter?
Dart supports string interpolation. Consider a code snippet as below:
var seconds = 5; print("Send $seconds seconds ago"); var harryLikes = 'Silvia'; var otherName = 'Erik'; var otherLikes = 'Chess'; print("Harry like $harryLikes"); print("I think $otherName like $otherLikes");
Also, more complex expressions can be embedded with ${…}
print('Calc 3 + 5 = ${3 + 5}');
The number of types and the intl package provide more methods to format numbers and dates.
You can also try the below examples:
You can also try the below way:
- Add the following to your pubspec.yaml
dependencies: sprintf: "^4.0.0"
then run pub install.
Next, import dart-sprintf:
import 'package:sprintf/sprintf.dart';
void main() { double seconds = 5.0; String name = 'Dilki'; List<String> pets = ['Cats', 'Dogs']; String sentence1 = sprintf('Sends %2.2f seconds ago.', [seconds]); String sentence2 = sprintf('Harry likes %s, I think %s likes %s.', [pets[0], name, pets[1]]); print(sentence1); print(sentence2); }
The output will look like the below :
Sends 5.00 seconds ago. Harry likes Cats, I think Dilki likes Dogs.
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.
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 your string would be interpolated.
Extensions
You can create an extension function that does something similar 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)
Testing
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); })
So you could also have something simple like this:
- Usage
interpolate('Hello {#}{#}, cool {#}',['world','!','?']); // Hello world!, cool ?
- Function
static const needleRegex = r'{#}'; static const needle = '{#}'; static final RegExp exp = new RegExp(needleRegex); static String interpolate(String string, List l) { Iterable<RegExpMatch> matches = exp.allMatches(string); assert(l.length == matches.length); var i = -1; return string.replaceAllMapped(exp, (match) { print(match.group(0)); i = i + 1; return '${l[i]}'; }); }
Conclusion:
Thanks for Reading. Hope you have enjoyed it.
So in this article, we have been through How to Format an Interpolated String In Flutter.
Keep Learning !!! Keep Fluttering !!!
Still, need Support for Flutter Development? Do let us know.
Flutter Agency is our portal Platform dedicated to Flutter Technology and Flutter Developers. The portal is full of cool resources from Flutter like Flutter Widget Guide, Flutter Projects, Code libs and etc.
Flutter Agency is one of the most popular online portals dedicated to Flutter Technology and daily thousands of unique visitors come to this portal to enhance their knowledge of Flutter.
Contemporary ventures
Recent blog
ready to get started?
Fill out the form below and we will be in touch soon!
"*" indicates required fields