我正在嘗試在我的顫振專案中使用 cubit 但我遇到了這個問題這個cubit里面有另一個功能,但我想先取消以前的功能,我該怎么做謝謝你的幫助。
class ConnectionCheckerCubit extends Cubit<ConnectionCheckerState> {
ConnectionCheckerCubit() : super(ConnectionCheckerInitial());
void whenConnectedFunction() {
print('test1');
}
void whenDisconnectedFunction() async {
print('test2');
await Future.delayed(Duration(seconds: 10));
print('test3');
}
}
我呼叫第二個函式whenDisconnectedFunction它的列印test2然后我呼叫上部函式whenConnectedFunction在10 秒結束它的列印test1但它也列印test3我該如何解決這個問題。謝謝 。
uj5u.com熱心網友回復:
一旦函式被呼叫,您就無法取消它,但是您可以做的是在未來完成后放置一個檢查器,以檢查該函式是否需要繼續進行。
我撰寫了一個示例代碼來幫助您更好地理解這一點,您可以粘貼 this is dartpad自己嘗試。
void main() async {
print("Testing without cancel");
final cubitWithoutCancel = ConnectionCheckerCubit();
cubitWithoutCancel.whenDisconnectedFunction();
cubitWithoutCancel.whenConnectedFunctionWithoutCancel();
await Future.delayed(const Duration(seconds: 11));
print("Testing with cancel");
final cubit = ConnectionCheckerCubit();
cubit.whenDisconnectedFunction();
cubit.whenConnectedFunction();
}
class ConnectionCheckerCubit {
ConnectionCheckerCubit();
bool _cancelFunctionIfRunning = false;
void whenConnectedFunction() {
_cancelFunctionIfRunning = true;
print('test1');
}
void whenConnectedFunctionWithoutCancel(){
print('test1');
}
void whenDisconnectedFunction() async {
print('test2');
await Future.delayed(Duration(seconds: 10));
if(_cancelFunctionIfRunning) return;
print('test3');
}
}
上述代碼的輸出如下:
Testing without cancel
test2
test1
test3
Testing with cancel
test2
test1
This is a rather simple implementation to help you understand the concept of how to quit a function midway based on an external factor, you can create a function to do this task for you instead of manually changing a boolean.
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/457144.html
