gpt4 book ai didi

flutter - 如何取消或伪取消 http 请求? - flutter

转载 作者:行者123 更新时间:2023-12-04 13:34:56 25 4
gpt4 key购买 nike

我有一个搜索栏,当输入字符时,它会向 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);
}
}
}
这是抓取数据的 future
  // 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;
}
}

我一直在用头撞墙,试图找出制作 BLoC 的解决方案 await为 future 还要让 SearchInitializeEvent取消正在提出的任何请求。
因为发生的事情发生在一个糟糕的网络上,所以请求无论如何都会尝试通过,并且在得到响应之前不会停止。
我知道你不能取消 future ,我都试过了 CancelableOperation和 'CancelableCompletion` 或其他任何名称。
我猜我必须将我的 Future 设置为 Stream 才能关闭它。我愿意接受任何建议。先感谢您!

最佳答案

使用 dart 来破坏 Streams 是有限制的。这是在“循环”之外无法完成的事情。这里详细讨论了这个问题:
https://github.com/dart-lang/sdk/issues/42717
https://github.com/felangel/bloc/issues/1472
您可能希望从不同的角度来研究这一点,例如覆盖最近请求所做的更改。或者,如果请求结果显示在屏幕上,则考虑不显示结果。

关于flutter - 如何取消或伪取消 http 请求? - flutter ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62767721/

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