我仍在加快使用 dart 的速度,并想知道是否有更簡單的方法可以在值為 null 時不執行陳述句。請參見下面的示例:
我總是可以執行下面的 if 陳述句來設定 field3 和 field4,但感覺像 field5 這樣的東西應該可以作業。但是當我嘗試這樣做時,它會抱怨在空值上使用了空檢查運算子。
此外,我不想將 Map 更改為具有動態值。
是否有一個班輪可以做我想做的事情,或者我只需要在設定值之前檢查 null 。
Map<String, Object> myMap = {};
print('running now');
try {
myMap['field1'] = DummyClass.getString('hello');
myMap['field2'] = DummyClass.getString('good');
//Is there a more concise way to do this than the 2 options below?
if (DummyClass.getOptionalString('goodbye') != null) {
myMap['field3'] = DummyClass.getOptionalString('goodbye')!;
}
String? temp = DummyClass.getOptionalString('go');
if (temp != null) {
myMap['field4'] = temp;
}
// This gives an error 'null check operator used on a null value'
// myMap['field5'] ??= DummyClass.getOptionalString('to')!;
} catch (e) {
print('error condition, $e');
}
print(myMap);
}
class DummyClass {
static String getString(String? strParam) {
String? retString = getOptionalString(strParam);
if (retString == null) {
throw ('nulls are not allowed');
}
return retString;
}
static String? getOptionalString(String? strParam) {
if (strParam == null || strParam.length < 3) {
return null;
}
return strParam;
}
}
uj5u.com熱心網友回復:
問題是??=如果它為空,則運算子分配給左邊。展開后,它看起來像這樣:
a ??= b;
// Equivalent to:
if (a == null) {
a = b;
}
這不是您想要實作的目標。AFAIK,Dart 中還沒有這樣的運算子。但是,你可以試試這個:
final possiblyNullValue = '';
final myMap = <String, String>{};
myMap['key'] = possiblyNullValue ?? myMap['key'];
// Equivalent to:
if (possiblyNullValue != null) {
myMap['key'] = possiblyNullValue;
}
// or:
myMap['key'] = possiblyNullValue != null? possiblyNullValue : myMap['key'];
在您的情況下,這將作為單線作業。
uj5u.com熱心網友回復:
您可以創建包含所有條目(甚至為 null)的地圖,然后過濾掉 null 值:
void main() {
try {
final myMap = <String, dynamic>{
'field1': DummyClass.getString('hello'),
'field2': DummyClass.getString('good'),
'field3': DummyClass.getOptionalString('goodbye'),
'field4': DummyClass.getOptionalString('go'),
}..removeWhere((k, v) => v == null);
print(myMap);
} catch (e) {
print('error condition, $e');
}
}
uj5u.com熱心網友回復:
沒有內置的方法可以做你想做的事,但你可以寫一個函式(或擴展方法)來做。例如:
extension MapTrySet<K, V> on Map<K, V> {
void trySet(K key, V? value) {
if (value != null) {
this[key] = value;
}
}
}
然后你可以這樣做:
myMap.trySet('field3', DummyClass.getOptionalString('goodbye'));
myMap.trySet('field4', DummyClass.getOptionalString('go'));
或者,如果您真的想使用普通Map語法,您可以創建自己的Map類,該類具有void operator []=(K key, V? value)覆寫并且在valueis時什么也不做null,但這可能不值得付出努力。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/434598.html
