在Dart中可以在这样的字符串中动态地注入许多变量值吗?
// Java code using String.format. In this case just 2 variables
String.format("Hello %s, You have %s years old", variable1, variable2)
谢谢
发布于 2020-08-04 13:00:29
还有其他的选择。最完整和最复杂的是使用用于MessageFormat的i18n。
https://pub.dev/documentation/intl/latest/message_format/MessageFormat-class.html
还有一个叫做“斯普林特”的飞镖酒吧套餐。它类似于Java中的printf ( C)或String.format。
将sprintf放入您的pubspec.yaml
dependencies:
sprintf:
Dart例子:
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);
}
对于更简单的情况,只需使用字符串内插:
print('Hello $name, the sum of 4+4 is ${4 + 4}.');
结果: Hello,4+4之和为8。
发布于 2020-04-22 12:17:49
在Dart中等效的是一个字符串内插:
"Hello $variable1, you are $variable2 years old"
如果要对变量进行抽象,可以使用普通函数:
String greet(String name, int age) =>
"Hello $name, you are $age years old";
对于任何固定数量的参数,您也可以这样做。
如果要传递格式字符串和相应的值数,则Dart没有varargs。相反,您可以为格式字符串创建一个函数,如上面所示,并使用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"]);
您会失去静态类型安全性,但是您也总是使用格式字符串。
发布于 2020-04-22 12:20:39
您可能希望创建一个类,如:
class MyString {
static format(String variable1, String variable2) {
return "Hello $variable1, you are $variable2 years old";
}
}
然后用它就像:
MyString.format("Bob", "10"); // prints "Hello Bob, you are 10 years old"
https://stackoverflow.com/questions/61364724
复制相似问题