Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String.format java method equivalent in dart

Tags:

flutter

dart

Is it possible in Dart to inject many variables values dynamically in a string like this ?

// Java code using String.format. In this case just 2 variables
String.format("Hello %s, You have %s years old", variable1, variable2)

Thanks

like image 260
Agnaramon Avatar asked Jun 12 '26 00:06

Agnaramon


2 Answers

There are some alternatives. The most complete and sophisticated is using MessageFormat that is used for i18n.
https://pub.dev/documentation/intl/latest/message_format/MessageFormat-class.html

And there is a dart pub package called "sprintf". It is similar to printf (in C) or String.format in Java.

Put sprintf in your pubspec.yaml

dependencies:
  sprintf:

Dart example:

import 'package:sprintf/sprintf.dart';

void main() {
  double score = 8.8;
  int years = 25;
  String name = 'Cassio';

  String numbers = sprintf('Your score is %2.2f points.', [score]);
  String sentence = sprintf('Hello %s, You have %d years old.', [name, years]);

  print(numbers);
  print(sentence);
}

For simpler cases you could just use String interpolation:

  print('Hello $name, the sum of 4+4 is ${4 + 4}.');

results: Hello Cassio, the sum of 4+4 is: 8.

like image 129
Cassio Seffrin Avatar answered Jun 14 '26 19:06

Cassio Seffrin


The equivalent in Dart is a string interpolation:

"Hello $variable1, you are $variable2 years old"

If you want to abstract over the variables, you can use a plain function:

String greet(String name, int age) =>
    "Hello $name, you are $age years old";

You can do the same for any fixed number of arguments.

If you want to pass a format string and a corresponding number of values, Dart does not have varargs. Instead you can create a function, like above, for the format string, and invoke it on a list of arguments using Function.apply:

String format(Function formatFunction, List<Object> values) => 
    Function.apply(formatFunction, values);

...
  format((a, b, c) => "The $a is $b in the $c!", ["dog", "lost", "woods"]);
  format((a, b) => "The $a is not $b!", ["status", "quo"]);

You lose static type safety, but you always did that with format strings too.

like image 34
lrn Avatar answered Jun 14 '26 20:06

lrn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!