gpt4 book ai didi

dart - map child 的有条件成员(member)访问权限?

转载 作者:行者123 更新时间:2023-12-03 02:53:25 30 4
gpt4 key购买 nike

假设您正在尝试访问 map 中深度嵌套的子级,并且您无法期望他们的 parent 在那里。示例:

Map awesomeMap = {
"this":{
"is":{
"sometimes":"not here"
}
}
}

Map notAwesomeMap = {
"this":{
"haha":{
"we":"switched"
}
}
}

当我访问 notAwesomeMap['this']['is']['sometimes'] 时,它将返回一个错误,因为 ['this']['is'] null,并且您无法查找 null 的值 ['sometimes']

所以这很好,但我希望能够使用条件成员访问运算符...

notAwesomeMap['这个']?.['是']?.['有时']

但这不起作用...

除了将所有内容包装在 try block 中之外,是否有一个好的方法来处理这些情况?

编辑:我尝试了一下,但没有发现任何真正有启发性的东西,但这也许会给某人一个想法

void main() {
Map nestedMap = {
'this':{
'is':{
'sometimes':'here'
}
}
};

final mapResult = nestedMap['this'];
print(mapResult); //returns {is: {sometimes: here}}

final nullResult = nestedMap['this']['is an'];
print(nullResult); // returns null


final nullifiedResult = nullify(nestedMap['this']['is an']['error']);
print(nullifiedResult); // returns error, but is this possible another way?

final errorResult = nestedMap['this']['is an']['error'];
print(errorResult); // returns error
}



nullify(object){
try {
final result = object;
return result;
}
catch (e) {
return null;
}
}

最佳答案

一种方法是

final result = (((nestedMap ?? const {})['this'] ?? const {})['is an'] ?? const {})['error'];

另请参阅Null-aware operator with Maps

关于dart - map child 的有条件成员(member)访问权限?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51408966/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com