Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/flutter/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Flutter 与dart中的String.format java方法等效_Flutter_Dart - Fatal编程技术网

Flutter 与dart中的String.format java方法等效

Flutter 与dart中的String.format java方法等效,flutter,dart,Flutter,Dart,在Dart中,是否可以像这样在字符串中动态注入许多变量值 // Java code using String.format. In this case just 2 variables String.format("Hello %s, You have %s years old", variable1, variable2) 谢谢Dart中的等效项是字符串插值: print('Hello $name, the sum of 4+4 is ${4 + 4}.'); “您好$variable

在Dart中,是否可以像这样在字符串中动态注入许多变量值

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

谢谢

Dart中的等效项是字符串插值:

  print('Hello $name, the sum of 4+4 is ${4 + 4}.');
“您好$variable1,您是$variable2岁”
如果要对变量进行抽象,可以使用普通函数:

String问候语(字符串名称,int-age)=>
“你好$name,你是$age岁”;
您可以对任何固定数量的参数执行相同的操作

如果要传递格式字符串和相应数量的值,Dart没有varargs。相反,您可以像上面那样为格式字符串创建一个函数,并使用
函数在参数列表上调用它。apply

String格式(函数formatFunction,列表值)=>
函数。应用(formatFunction,value);
...
格式((a,b,c)=>“a是$c中的$b!”,[“dog”,“lost”,“woods”]);
格式((a,b)=>“a不是b!”,[“状态”,“现状]);

您失去了静态类型安全性,但您也总是使用格式字符串来实现这一点。

您可能需要创建一个类,如:

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"

还有一些选择。最完整、最复杂的是使用i18n使用的MessageFormat。

还有一个叫“sprintf”的dart酒吧套餐。它类似于C中的printf或Java中的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}.');

结果:你好,凯西奥,4+4之和是:8。

为什么?这在很大程度上脱离了question@iamyadunandan只是为了提供另一种实现的方法。在这种情况下,只有两个变量。3,4,n变量是什么?使用Java中的String.format方法,我们可以传递很多arguments@Agnaramon我理解,但Dart中不存在java的
Strings.format
等价物。在本例中,它只有两个变量。3,4,n变量是什么?使用Java中的String.format方法,我们可以传递这么多参数。在答案中添加了一些相关内容。听起来是一种很酷的方法!我认为dart框架中有一种方法实现了这一点