You need to enable JavaScript to run this app. Flutter Web使用http 0.12.2调用接口报Unsupported operation: Platform._version求解决
优惠活动
大模型
产品
解决方案
定价
更多

Flutter Web使用http 0.12.2调用接口报Unsupported operation: Platform._version求解决

问题原因

你当前代码报错的核心原因是IOClient、HttpClient都来自dart:io库,而Flutter Web环境完全不支持dart:io相关API,调用的时候就会触发Unsupported operation: Platform._version的平台不兼容错误。另外你设置的badCertificateCallback跳过证书校验的逻辑,在Web环境下本身也不生效——Web的证书校验完全由浏览器控制,前端代码无法篡改。

解决步骤

1. 用条件导入区分平台实现Client初始化逻辑

通过Flutter的条件导入能力,分别为原生端(Android/iOS)和Web端实现不同的Client初始化逻辑,自动适配平台:

第一步:抽离Client初始化抽象层

新建http_client.dart文件:

import 'package:http/http.dart' as http;

export 'http_client_stub.dart'
    // 原生端导入io实现
    if (dart.library.io) 'http_client_io.dart'
    // Web端导入html实现
    if (dart.library.html) 'http_client_html.dart';

abstract class HttpClientAdapter {
  http.Client getClient();
}

第二步:实现默认占位逻辑http_client_stub.dart

import 'http_client.dart';

HttpClientAdapter getClient() => throw UnimplementedError('不支持当前平台');

第三步:实现原生端逻辑http_client_io.dart

import 'dart:io';
import 'package:http/http.dart' as http;
import 'package:http/io_client.dart';
import 'http_client.dart';

class IOHttpClientAdapter implements HttpClientAdapter {
  @override
  http.Client getClient() {
    var ioClient = HttpClient()
      ..badCertificateCallback = (X509Certificate cert, String host, int port) => true;
    return IOClient(ioClient);
  }
}

HttpClientAdapter getClient() => IOHttpClientAdapter();

第四步:实现Web端逻辑http_client_html.dart

import 'package:http/http.dart' as http;
import 'package:http/browser_client.dart';
import 'http_client.dart';

class WebHttpClientAdapter implements HttpClientAdapter {
  @override
  http.Client getClient() {
    // Web端使用BrowserClient,不需要也不能设置证书跳过逻辑
    return BrowserClient();
  }
}

HttpClientAdapter getClient() => WebHttpClientAdapter();

2. 改造ApiService适配多平台

class ApiService {
   // 直接通过抽象层获取对应平台的Client,无需手动判断平台
   late final http.Client client = getClient().getClient();

   Future<String> login(String user, String pass) async {
   try {
       var response = await client.post(
           // 注意:Web端请求必须补全http/https协议头,否则会被浏览器识别为相对路径
           Uri.parse('http://192.168.1.1:1234/api/abc'),
           headers: <String, String>{
             'Content-Type': 'application/json; charset=UTF-8',
           },
           body: jsonEncode(<String, String>{'username': user, 'matkhau': pass}),
         );
         if (response.statusCode == 200) {
             print('ok');
             return response.body;
         } else {
             return null;
         }
    }catch (e) {
       print(e);
       return null;
    }
  }
}

3. 额外注意Web端跨域问题

适配逻辑修改完成后如果Web端还出现CORS错误,需要在服务端配置允许跨域请求,Flutter Web端本身无法绕过浏览器的跨域限制。

内容的提问来源于stack exchange,提问作者kevin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.10 11:36:03