标签: dio

iOS 有 INTERNET 权限吗?

我在 iOS 设备上的 flutter dio 包上遇到了一个奇怪的问题。\ni 编写了一个向 url 发送 GET 请求的应用程序。在 Android 上一切正常,但在 iOS 上看起来请求没有通过。\n什么也没发生,没有错误,什么也没有。我在 Android 上也遇到了同样的问题,但我发现我忘记将 INTERNET 权限添加到我的清单文件中。我猜iOS也会发生同样的情况。

\n\n

iOS 中是否有任何 INTERNET 权限需要添加 info.plist ?

\n\n
void _checkVersionAndPreferences() async {\n    SharedPreferences prefs = await SharedPreferences.getInstance();\n    String prefsRes = prefs.getString('access_token') ?? '';\n    String buildNumber = _packageInfo.buildNumber ?? '1';\n    Dio dio = Dio();\n    _cancelToken = CancelToken();\n    Future.delayed(Duration(seconds: 10), () {\n      if (_getRequestSuccess == false) {\n        _cancelToken.cancel();\n        _checkVersionAndPreferences();\n        _showSnackBar(\n            content: '\xd8\xaa\xd9\x84\xd8\xa7\xd8\xb4 \xd9\x85\xd8\xac\xd8\xaf\xd8\xaf \xd8\xa8\xd8\xb1\xd8\xa7\xdb\x8c \xd8\xa8\xd8\xb1\xd9\x82\xd8\xb1\xd8\xa7\xd8\xb1\xdb\x8c \xd8\xa7\xd8\xb1\xd8\xaa\xd8\xa8\xd8\xa7\xd8\xb7',\n            duration: Duration(seconds: 3),\n            leading: Icon(Icons.refresh, color: Colors.black));\n …
Run Code Online (Sandbox Code Playgroud)

ios dart flutter dio

6
推荐指数
1
解决办法
2万
查看次数

Flutter web - dio将post请求改为options请求

我正在package:dioFlutter Web 应用程序中使用。

然而,每当我发送 POST 请求时,它就会更改为 OPTIONS 请求。发出 API 请求的函数如下所示:

Future<LoginResponse> login(LoginRequest request) async {
    final dio = Dio(BaseOptions(baseUrl: "http://localhost:8000"));
    final response = await dio.post("/login", data: request.toJson());
    return LoginResponse.fromJson(jsonDecode(response.data));
}
Run Code Online (Sandbox Code Playgroud)

此代码将OPTIONS请求发送到http://localhost:8000/login. 如果我将该端点添加到我的服务器,它就可以工作。

如果我手动从邮递员发送 POST 请求,它也可以工作。

如果我将此代码更改为其他方法(例如dio.delete(...)),它也会映射到OPTIONS请求。

为什么要dio重写我的请求?

http dart flutter flutter-web dio

6
推荐指数
1
解决办法
4188
查看次数

Flutter:读取 BloC 状态的 Stream 数据,如果发生变化则重新渲染 UI

我在使用 BloC 模式并结合使用 Dio 显示下载过程时遇到问题。

谁能告诉我,如何从 dio 获取 onUploadProgress 进入块状态并在状态内的进度更新时显示它?

目前我有 UI、BloC 和 API 类。我需要将我的块传递到 API 调用中以下载文件,然后添加一个额外的事件,如下所示:

onReceiveProgress: (int received, int total) => {
          bloc.add(DownloadingImages((received / total) * 100))
        });
Run Code Online (Sandbox Code Playgroud)

我还发现了一个大问题,但我不知道如何以干净的方式解决。如果我添加 DownloadingImage 状态并传递该过程,它不会更新 UI。发生这种情况是因为状态不会改变,而只是状态内部的值发生变化。BlocBuilder 无法识别状态内部的值变化,也不会重新渲染 UI...

所以我有另一个解决方法(BloC):

if (state is ImagesDownloading) {
          imageBloc.add(DownloadingImages2(state.progress));
          if (state.progress < 100) {
            return DownloadAndProgressWidget(
                done: false, progress: state.progress);
          } else {
            return DownloadAndProgressWidget(done: true, progress: 100);
          }
        } else if (state is ImagesDownloading) {
          imageBloc.add(DownloadingImages2(state.progress));
          if (state.progress < 100) {
            return DownloadAndProgressWidget(
                done: false, …
Run Code Online (Sandbox Code Playgroud)

state-management dart flutter bloc dio

5
推荐指数
0
解决办法
877
查看次数

Flutter Dio Package:如何监听另一个类的下载进度?

我有一个DownloadsService类使用包处理文件下载dio。我想听一下我的ViewModel类中实现类downloadFile内方法的下载进度DownloadService。我该怎么做呢?

这是我的DownloadsService课程代码片段:

class DownloadsService {
   final String urlOfFileToDownload = 'http://justadummyurl.com/'; //in my actual app, this is user input
   final String filename = 'dummyfile.jpg';
   final String dir = 'downloads/$filename'; //i'll have it saved inside internal storage downloads directory

   void downloadFile() {
     Dio dio = Dio();
     dio.download(urlOfFileToDownload, '$dir/$filename', onReceiveProgress(received, total) {
        int percentage = ((received / total) * 100).floor(); //this is what I want to listen to from my ViewModel …
Run Code Online (Sandbox Code Playgroud)

progress stream listen flutter dio

5
推荐指数
1
解决办法
1万
查看次数

类型“_OneByteString”不是类型“Map &lt;String,dynamic&gt;”的子类型

当我尝试解析我发出的网络请求的响应正文到 json 映射时,这是我仅在发布模式(奇怪)下遇到的错误。我写下了代码以及下面的错误堆栈跟踪。我应该提到的另一件奇怪的事情是,它只是有时会发生。并非一直如此。但对于我在市场上发布的应用程序,当我检查 Firebase 上的崩溃报告时,也会报告此错误。(不过,它不会导致崩溃)

我应该提到我使用 Dio 包作为 http 客户端

更新: 我发现它有时会发生,但是当它发生时,当我一遍又一遍地发送相同的请求或有时发送其他请求时,它会不断发生。直到我退出应用程序并再次运行它。

错误堆栈跟踪:

I/flutter (31714): type '_OneByteString' is not a subtype of type 'Map<String, dynamic>'
I/flutter (31714): #0      Server.getUser (package:mehrgan/data/network/server.dart:83)
I/flutter (31714): <asynchronous suspension>
I/flutter (31714): #1      Future.wait.<anonymous closure> (dart:async/future.dart:0)
I/flutter (31714): <asynchronous suspension>
I/flutter (31714): type '_OneByteString' is not a subtype of type 'Map<String, dynamic>'
I/flutter (31714): #0      Server.getCourses (package:mehrgan/data/network/server.dart:101)
I/flutter (31714): <asynchronous suspension>
I/flutter (31714): #1      Future.wait.<anonymous closure> (dart:async/future.dart:0)
I/flutter (31714): <asynchronous suspension>
Run Code Online (Sandbox Code Playgroud)

我的代码:

Response response = await …
Run Code Online (Sandbox Code Playgroud)

dart flutter dio

5
推荐指数
1
解决办法
6815
查看次数

为什么flutter dio拦截器不调用该方法?

我正在开发一个使用 JWT 访问后端端点的 Flutter 应用程序。当访问令牌过期时,我添加了一个拦截器以根据此处提供的解决方案刷新令牌: Using Interceptor in Dio for Flutter to Refresh Token 我可以看到显示 401 的服务器日志。

这是我的代码:

import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:dummy/utils/config.dart';

Future<Response> uploadVideo(filePath, fileName, title, jwt) async {
  Dio dio = new Dio();
  var token = json.decode(jwt);
  dio.interceptors.clear();

  dio.options.headers["Authorization"] = "Bearer ${token['access']}";
  dio.interceptors.add(InterceptorsWrapper(onError: (error) async {
    print(error.response);
    if (error.response?.statusCode == 403 ||
     error.response?.statusCode == 401) {
    await refreshToken(jwt);
    _retry(error.request, dio);
     }
    return error.response;
  }));
  Response response;
  try {
    FormData formData = FormData.fromMap({
      "file_name": fileName,
      "content": await MultipartFile.fromFile(filePath), …
Run Code Online (Sandbox Code Playgroud)

dart flutter flutter-dependencies dio

5
推荐指数
1
解决办法
2818
查看次数

Flutter Dio 拦截器错误:错误状态:Future 已完成

我有一个拦截器可以在 jwt 过期时发送jwt token和使用端点。refresh_token有了过期的 jwt 我得到

Error: Bad state: Future already completed
Run Code Online (Sandbox Code Playgroud)

错误,但请求仍然被正确处理。在控制台中,我看到一个成功的响应,另一个随后出现 401 错误。我该如何解决这个问题?

自定义拦截器.dart

class CustomInterceptor extends DefaultInterceptor {
  ISecureStorage secureStorageService = ISecureStorage();

  @override
  void onRequest(
      RequestOptions options, RequestInterceptorHandler handler) async {
    LoginModel loginModel = await secureStorageService.readLoginModel();

    options.headers = {
      "Content-type": "application/json",
      "Authorization": "Bearer ${loginModel.access_token}"
    };
    return super.onRequest(options, handler);
  }

  @override
  void onError(err, handler) async {
    if (err.response?.statusCode == 401) {
      final Dio _dio = DioConfig().dio;
      LoginModel loginModel = await secureStorageService.readLoginModel();
      Uri uri = …
Run Code Online (Sandbox Code Playgroud)

interceptor dart flutter dio

5
推荐指数
1
解决办法
1万
查看次数

flutter中api调用哪种方式最好

我是颤振开发的新手。最近听说了Dio和Http包用于api调用。这是 api 调用最好的一个。如果有人有更好的api服务方式?

  CreateAccountRepository.internal();

  static final CreateAccountRepository _singleInstance =
      CreateAccountRepository.internal();

  factory CreateAccountRepository() => _singleInstance;

  //api: Registration
  Future<CreateAccountResponse> userRegistration(
      AccountCreateRequest requestParams) async {
    bool isNetworkAvail = await NetworkCheck().check();
    if (isNetworkAvail) {
      final response = await networkProvider.call(
          method: Method.POST,
          pathUrl: AppUrl.pathRegister,
          body: requestParams.toJson(),
          headers: headerContentTypeAndAccept);
      if (response.statusCode == HttpStatus.ok) {
        String location = response.headers['location'];
        String userId = location.split("/").last;
        CreateAccountResponse createAccountResponse =
            CreateAccountResponse.fromJson(json.decode(response.body));
        createAccountResponse.isSuccess = true;
        createAccountResponse.userId = int.parse(userId);
        return createAccountResponse;
      } else if (response.statusCode == HttpStatus.unprocessableEntity) {
        return CreateAccountResponse.fromJson(json.decode(response.body));
      } else if …
Run Code Online (Sandbox Code Playgroud)

api rest flutter dio flutter-http

5
推荐指数
1
解决办法
7238
查看次数

减少 Flutter 中 API 的连接等待时间

我正在尝试优化 Flutter 应用程序的 API 响应时间。我有一个 API,其中添加了服务器级缓存,并且我正在使用Dio来满足我的 API 需求。

在 Postman 上测试时的响应时间约为 100 毫秒。在 Chrome 开发者工具上获取类似的指标。

问题是,当我在 Flutter DevTools 上测量响应时间时,所有响应都 >250 毫秒。经过检查,我发现每个请求的连接等待时间约为 200 毫秒。

邮递员要求无需等待时间

在开发工具上看到连接等待时间较长

如何减少Flutter的上述等待时间?

我尝试切换库并重用此处和http文档中建议的相同 https 客户端,但后续请求的等待时间仍然相似。

var client = http.Client();
final res = await client.get(...);
Run Code Online (Sandbox Code Playgroud)

如何避免这些连接延迟并获得最佳性能?如果缓存 SSL、DNS 查找等是解决方案,那么我该如何在 flutter 中做到这一点?

https caching flutter dio

5
推荐指数
1
解决办法
2040
查看次数

Flutter 错误:连接出错:调用了 XMLHttpRequest onError 回调。这通常表示网络层出现错误

当我向标头添加新值(例如 account-type)时,我从 dio 库收到以下错误

\n
\n

DioExceptionType.connectionError\n\xe2\x95\x91 连接出错:调用了 XMLHttpRequest onError 回调。这通常表示网络层出现错误。

\n
\n
return await _dio.get(\n  "payment/test/",\n  options: Options(headers: {\n    'account-type': 'master',\n    'Authorization': authorize.user.access,\n    'Accept': 'application/json',\n  }),\n);\n
Run Code Online (Sandbox Code Playgroud)\n

dart flutter dio

5
推荐指数
0
解决办法
6103
查看次数