Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/flutter/9.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/dart/3.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和Flatter中的int中_Flutter_Dart - Fatal编程技术网

Flutter 有没有更好的方法将前导零添加到dart和Flatter中的int中

Flutter 有没有更好的方法将前导零添加到dart和Flatter中的int中,flutter,dart,Flutter,Dart,我为dart int创建了一个扩展来添加前导零,我想知道是否有更优雅的方法?我的看法是: extension IntExtensions on int { ///returns a String with leading zeros. ///1 would be with the [numberOfTotalDigits] = 3 lead to a string '001' String addLeadingZeros(int numberOfTotalDigits) {

我为dart int创建了一个扩展来添加前导零,我想知道是否有更优雅的方法?我的看法是:

extension IntExtensions on int {
  ///returns a String with leading zeros.
  ///1 would be with the [numberOfTotalDigits] = 3 lead to a string '001'
  String addLeadingZeros(int numberOfTotalDigits) {
    var valueAsString = this.toString();
    var buffer = StringBuffer();
    if (valueAsString.length < numberOfTotalDigits) {
      var addLeadingZeros = numberOfTotalDigits - valueAsString.length;
      for (int i = 0; i < addLeadingZeros; i++) buffer.write('0');
    }
    return '${buffer.toString()}$valueAsString';
  }
}
像这样

extension IntExtensions on int {
  ///returns a String with leading zeros.
  ///1 would be with the [numberOfTotalDigits] = 3 lead to a string '001'
  String addLeadingZeros(int numberOfTotalDigits) =>
      toString().padLeft(numberOfTotalDigits, '0');
}
extension IntExtensions on int {
  ///returns a String with leading zeros.
  ///1 would be with the [numberOfTotalDigits] = 3 lead to a string '001'
  String addLeadingZeros(int numberOfTotalDigits) =>
      toString().padLeft(numberOfTotalDigits, '0');
}