我目前在一个块中有一个函数,它调用我的存储库,使用GraphQL从我的服务器上获取数据。我可以拿回数据了。但是,我无法将其返回到我的块中,因为函数在获取数据后退出。
这是我代码块中的代码……
Either<AuthFailure, GLoginData_login> failureOrSuccess;
failureOrSuccess = await loginWithUsernameAndPassword(username: state.username, password: state.password)
.whenComplete(() { <---------- This line is never triggered (why not?)
failureOrSuccess.fold((l) => null, (r) {
print('You have the data $r');
});
});正如您所看到的,我正在等待forwardedCall的响应。
下面是我的存储库中的代码,该代码块调用....
abstract class LoginRepository<TData, TVars, TRequest extends OperationRequest<TData, dynamic>> {
Future<Either<AuthFailure, GLoginData_login>> loginWithUsernameAndPassword({
@required Username username,
@required Password password,
});
}此存储库是一个抽象类,其中的方法在以下类中实现...
class LoginUser extends LoginRepository {
@override
Future<Either<AuthFailure, GLoginData_login>> loginWithUsernameAndPassword(
{@required Username username, @required Password password}) =>
_runQuery(username: username, password: password);
Future<Either<AuthFailure, GLoginData_login>> _runQuery(
{@required Username username, @required Password password}) async {
final loginReq = GLoginReq(
(b) => b
..vars.LoginInput.username = usernameStr
..vars.LoginInput.password = passwordStr,
);
try {
return await GetIt.instance<Client>().request(loginReq).listen((response) {
if (!response.loading && response.dataSource == DataSource.Link &&
response.data != null) {
GLoginData data = response.data;
GLoginData_login login = data.login;
return login;
}
if (response.linkException != null) {
return response.graphqlErrors;
}
}).asFuture(); <------ I am marking it as a future so that it can be passed back
} on Exception catch (e) {
// Will need a created AuthException depending on our API and requirements
if (e.toString() == 'ERROR_NO_ACCOUNT_MATCHES_DETAILS_GIVEN') {
return left(const AuthFailure.invalidUsernameAndPaswordCombination());
} else {
return left(const AuthFailure.serverError());
}
}
}
}我确实从服务器接收到了客户端响应的数据。然而,在我的代码块中,我不能对它做任何事情,因为它只是在loginWithUsernameAndPassword函数完成后跳出代码块。
如何在块中使用返回值,whenComplete值行不起作用。
感谢您能提供的任何帮助。
发布于 2021-11-11 23:03:13
只需这样做:
either.fold(
(l) => Something(),
(r) => Something(),
);如果您有一个返回值的函数,则将l或r放入该函数。
https://stackoverflow.com/questions/66377114
复制相似问题