在 Dart 中是否可以在这样的字符串中动态注入许多变量值?
// Java code using String.format. In this case just 2 variables
String.format("Hello %s, You have %s years old", variable1, variable2)
Run Code Online (Sandbox Code Playgroud)
谢谢
有一些替代方案。最完整和最复杂的是使用用于 i18n 的 MessageFormat。
https://pub.dev/documentation/intl/latest/message_format/MessageFormat-class.html
还有一个名为“sprintf”的 dart pub 包。它类似于 printf(在 C 中)或 Java 中的 String.format。
将 sprintf 放在您的 pubspec.yaml 中
dependencies:
sprintf:
Run Code Online (Sandbox Code Playgroud)
飞镖示例:
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);
}
Run Code Online (Sandbox Code Playgroud)
对于更简单的情况,您可以只使用字符串插值:
print('Hello $name, the sum of 4+4 is ${4 + 4}.');
Run Code Online (Sandbox Code Playgroud)
结果:你好卡西欧,4+4的总和是:8。
| 归档时间: |
|
| 查看次数: |
2135 次 |
| 最近记录: |