长期潜伏者第一次海报。
学习Dart并使用Dart_code_metrics确保我编写的代码符合预期。活动的规则之一是避免非空断言。
注意,创建下面的代码是为了在更大的代码库中重新创建遇到的问题,其中unitString的值取自JSON文件。因此,程序无法控制JSON文件中指定的内容。
来自pubspec.yaml
environment: sdk: '>=2.15.0 <3.0.0'
// ignore_for_file: avoid_print
import 'package:qty/qty.dart';
void main() {
const String unitString = 'in';
// unit.Width returns null if unitString is not a unit of Length.
if (Length().unitWith(symbol: unitString) == null) {
print('units $unitString not supported.');
} else {
// The following line triggers avoid-non-null-assertion with the use of !.
final Unit<Length> units = Length().unitWith(symbol: unitString)!;
final qty = Quantity(amount: 0.0, unit: units);
print('Qty = $qty');
}
}
如果我不使用!然后我得到以下类型错误:
A value of type 'Unit<Length>?' can't be assigned to a variable of type 'Unit<Length>'. Try changing the type of the variable, or casting the right-hand type to 'Unit<Length>'.
将右侧铸造至
Unit<Length>
修复了上述错误,但在实例化Quantity()时会导致新的错误,因为构造函数需要
Unit<Length>
而不是
Unit<Length>?
我假设有一个解决方案,但我是Dart的新手,无法制定正确的搜索查询来找到答案。
如何修改示例代码以使Dart和Dart_code_metrics满意?