gpt4 book ai didi

Flutter 卡住,使用联合/密封类时如何返回值并停止执行函数

转载 作者:行者123 更新时间:2023-12-05 06:10:19 25 4
gpt4 key购买 nike

我有这个方法,我使用卡住的 flutter 包来处理网络状态。

我想停止异步方法的执行,以防我使用联合/密封类收到失败响应。

 void wantedToStopExecutionInAsync() async {
var resultFromNetworkCall = await myNetworkCall();

resultFromNetworkCall.when(
success: (value) {
//do some work;
},
failure: (exception) {
print(exeption);
//Here I want to stop the execution of async function wantedToStopExecutionInAsync()
return;
}
);

//If result is a failure, I dont want to process the next line of code
someOtherWork();
}

我想在收到失败响应时停止执行,这可能吗?

一个选项是

 void wantedToStopExecutionInAsync() async {
var resultFromNetworkCall = await myNetworkCall();

resultFromNetworkCall.when(
success: (value) {
//do some work;
},
failure: (exception) {
print(exeption);
//Here I want to stop the execution of async function wantedToStopExecutionInAsync()
return;
}
);

if (resultFromNetworkCall is Failure) {
return;
}

//If result is a failure, I dont want to process the next line of code
someOtherWork();
}

但这并不好。有什么建议吗?

最佳答案

没那么难。在联合中返回一个 bool 结果。检查下一个代码片段:

void wantedToStopExecutionInAsync() async {
var resultFromNetworkCall = await myNetworkCall();

bool success = resultFromNetworkCall.when(
success: (value) {
return true;
},
failure: (exception) {
print(exeption);
return false; // NOTE: Return of false
},
);

//Stop the execution of async function wantedToStopExecutionInAsync()
if (success == false || resultFromNetworkCall is Failure) {
return;
}

//If result is a failure, I dont want to process the next line of code
someOtherWork();
}

关于Flutter 卡住,使用联合/密封类时如何返回值并停止执行函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64475610/

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