Flutter分析方法解释



我有一个格式为Month-Day-4DigitYear的字符串日期,我想在Flutter中将其转换为DateTime。我是一个程序员新手,我很难理解api.flutter.dev解析方法的例子。

以下是示例。我只是有几个问题。当我刚创建一个类并放入这个函数时,Android Studio会抛出多个错误。我想我理解不可为null的问题,所以我删除了!和标记无处不在。

我的问题是:什么是_parseFormat、_brokenDownDateToValue和_withValue?

所有这些都会产生错误,仅仅声明前两个并删除_withValue似乎并没有起到什么作用,尽管它会删除所有错误。这就像他们遗漏了我缺少的一个关键部分,或者有一个我需要导入的包,我和安卓工作室都不知道。有人能解密这个吗?我对flutter的文档感到非常沮丧,因为它似乎总是提供80%的所需信息,假设你已经对除他们正在讨论的这一主题之外的所有其他主题都有洞察力。在阅读手册之前,必须先成为专业人士。

// TODO(lrn): restrict incorrect values like  2003-02-29T50:70:80.
// Or not, that may be a breaking change.
static DateTime parse(String formattedString) {
var re = _parseFormat;
Match? match = re.firstMatch(formattedString);
if (match != null) {
int parseIntOrZero(String? matched) {
if (matched == null) return 0;
return int.parse(matched);
}
// Parses fractional second digits of '.(d+)' into the combined
// microseconds. We only use the first 6 digits because of DateTime
// precision of 999 milliseconds and 999 microseconds.
int parseMilliAndMicroseconds(String? matched) {
if (matched == null) return 0;
int length = matched.length;
assert(length >= 1);
int result = 0;
for (int i = 0; i < 6; i++) {
result *= 10;
if (i < matched.length) {
result += matched.codeUnitAt(i) ^ 0x30;
}
}
return result;
}
int years = int.parse(match[1]!);
int month = int.parse(match[2]!);
int day = int.parse(match[3]!);
int hour = parseIntOrZero(match[4]);
int minute = parseIntOrZero(match[5]);
int second = parseIntOrZero(match[6]);
int milliAndMicroseconds = parseMilliAndMicroseconds(match[7]);
int millisecond =
milliAndMicroseconds ~/ Duration.microsecondsPerMillisecond;
int microsecond = milliAndMicroseconds
.remainder(Duration.microsecondsPerMillisecond) as int;
bool isUtc = false;
if (match[8] != null) {
// timezone part
isUtc = true;
String? tzSign = match[9];
if (tzSign != null) {
// timezone other than 'Z' and 'z'.
int sign = (tzSign == '-') ? -1 : 1;
int hourDifference = int.parse(match[10]!);
int minuteDifference = parseIntOrZero(match[11]);
minuteDifference += 60 * hourDifference;
minute -= sign * minuteDifference;
}
}
int? value = _brokenDownDateToValue(years, month, day, hour, minute,
second, millisecond, microsecond, isUtc);
if (value == null) {
throw FormatException("Time out of range", formattedString);
}
return DateTime._withValue(value, isUtc: isUtc);
} else {
throw FormatException("Invalid date format", formattedString);
}
}

我的问题是:什么是_parseFormat、_brokenDownDateToValue和_withValue?

这些是在库中其他地方声明的私有对象或函数(作为第一个字符的_将对象和函数声明为私有(,因此未在文档中显示。

  • _parseFormat似乎是一个正则表达式。

  • CCD_ 3似乎是一个函数。

  • _withValue是一个命名构造函数。

如果您想将日期字符串解析为DateTime对象,我认为您需要使用以下内容。

var date = "11-28-2020"; // Month-Day-4DigitYear
var dateTime = DateTime.parse(date.split('-').reversed.join());

请参阅https://api.flutter.dev/flutter/dart-core/DateTime/parse.html以便解析接受的字符串。

我确实在这里找到了完整的代码示例。

它没有使用名称_parseFormat,而是只使用RegExp?并且具有_withValue和_brokenDownDateToValue声明。

在我看来,没有正确的方法来解读他们的例子。这个例子是不够的。字典不应该使用字典中其他地方找不到的单词来创建定义。

最新更新