flutter中如何实现sprintf方法格式化字符串输出?

码云
2020-11-13 09:02

flutter/dart中默认是不支持sprintf的,可以借助于第三方插件sprintf来实现,示例代码如下:

  • 导入依赖包
dependencies:
  sprintf: "^4.0.0"
  • 代码示例
import 'package:sprintf/sprintf.dart';

void main() {
  double seconds = 5.0;
  String name = 'Dilki';
  List<String> pets = ['Cats', 'Dogs'];

  //格式化输出,指定浮点数的格式
  String sentence1 = sprintf('Sends %2.2f seconds ago.', [seconds]);
  //格式化输出
  String sentence2 = sprintf('Harry likes %s, I think %s likes %s.', [pets[0], name, pets[1]]);

  print(sentence1);
  print(sentence2);

  //输出结果
  //Sends 5.00 seconds ago.
  //Harry likes Cats, I think Dilki likes Dogs.
}

 

全部评论