Skip to content
DeveloperMemos

Using sprintf in Flutter/Dart

Flutter, Dart1 min read

If you're reading this post you are probably looking for something similar to printf or String.format in Dart. Unfortunately the same functionality isn't supported in Flutter/Dart out of the box. There is a third party package though.

Before I talk about the sprintf package I'd like to mention that there is string interpolation in Dart. Here's a really simple example:

1var greeting = "Hello";
2var world = "World";
3
4print("${greeting}, ${world}!");

The code above would print "Hello, world!". But what you can't do is something like the Java code below:

1String output = String.format("%s is %d", "Joe", 35); // output is 'Joe is 35'

There's a pretty lengthy discussion on Github about this feature, if you're interested in reading it you can find it here. It looks like they have no plans of adding the feature to Dart for the time being.

And if you're looking for a good package, I've tried dart-sprintf on pub and it works well. To install it just add this to your pubspec.yaml:

1dependencies:
2 sprintf: ^4.0.2

Here's a usage example:

1import 'package:sprintf/sprintf.dart';
2
3void main() {
4 print(sprintf("%s %s", ["Hello", "World!"]));
5}

And that's pretty much all there is to it. I haven't had many gripes with Dart, it's been a lot better than other languages I have used before but it is kind of strange that they have no plans to add this kind of feature.