我有一个搜索栏,当输入字符时,它会向 BLoC 发送请求,然后 BLoC 从 Future 请求数据。
这是 BLoC
import 'dart:async';
import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:stockrails/models/semantics/error-type-model.dart';
import 'package:stockrails/models/user-interface/search-query-model.dart';
import 'package:stockrails/services/apis/stock-data.dart';
import 'package:stockrails/shared/constants/messages.dart';
part 'search_event.dart';
part 'search_state.dart';
class SearchBloc extends Bloc<SearchEvent, SearchState> {
SearchBloc() : super(SearchInitial());
// Connection to api service
StockData _data = StockData();
@override
Stream<SearchState> mapEventToState(
SearchEvent event,
) async* {
// : Initial search state - no text has been entered, no loading
if (event is SearchIntializeEvent) {
yield SearchInitial();
}
// : Querying search state - text is being entered, loading next
if (event is SearchQueryingEvent) {
// Yields call
yield* _mapAPICallToEvent(event.query);
}
}
// + ----------- Functions -------------
Stream<SearchState> _mapAPICallToEvent(String query) async* {
// : Yield loading screen based on prior state
if (state is SearchErrorState)
yield SearchErrorLoadingState();
else
yield SearchLoadingState(query: query);
// : Attempts to call method
List<SearchQueryModel> _result;
try {
_result = await _data.searchQuery(query);
} on TimeoutException {
_result = null;
} catch (err) {
_result = [];
}
// : If it can't then it defaults to using the unknownErrorMessage
if (_result == null)
yield SearchErrorState(errorMessage: Messages.unknownErrorMessage, errorType: ErrorType.errorTypes[0]);
// : Else if there's no content in the response
else if (_result.length == 0)
yield SearchErrorState(errorMessage: query, errorType: ErrorType.errorTypes[1]);
// : If there's no errors return loaded!
else {
yield SearchLoadedState(searchQueryModelList: _result, query: query);
}
}
}
Run Code Online (Sandbox Code Playgroud)
这就是获取数据的未来
// Grabs data from endpoint and returns or errors
// If it times out it will throw a TimeoutException
Future _dataFetch(String url, String query, String token) async {
try {
// Build out auth header
final authHeader = 'Bearer $token';
final response = await http
.get(url, headers: <String, String>{
'query': query,
'authorization': authHeader,
})
.timeout(Duration(seconds: 10))
.catchError((error) {
throw error;
});
// Makes sure response is okay
if (response.statusCode == 200) {
return json.decode(response.body);
}
// If status code is unknown, prints an error
else {
throw Exception(Messages.unknownErrorMessage);
}
} on TimeoutException catch (error) {
throw error;
} on SocketException catch (error) {
throw error;
} catch (error) {
throw error;
}
}
Run Code Online (Sandbox Code Playgroud)
我一直在绞尽脑汁,试图找到一个解决方案,await既可以为未来打造 BLoC,又可以SearchInitializeEvent取消任何正在提出的请求。
因为发生的情况是在一个糟糕的网络上发生的,所以无论如何,请求都会尝试通过,并且在得到响应之前不会停止。
我知道你不能取消期货,我尝试了两者CancelableOperation或CancelableCompletion无论它被称为什么。
我猜我必须将我的 Future 设置为 Stream,这样我才能关闭它。我愿意接受任何建议。先感谢您!
dart 在破坏 Stream 方面存在限制。这是在“循环”之外无法完成的事情。这个问题在这里进行了详细讨论:
https://github.com/dart-lang/sdk/issues/42717
https://github.com/felangel/bloc/issues/1472
您可能想从不同的角度来研究这个问题,例如覆盖最近请求所做的更改。或者,如果请求结果显示在屏幕上,则考虑不显示结果。
| 归档时间: |
|
| 查看次数: |
11059 次 |
| 最近记录: |