Flutter从API读取阿拉伯文本显示异常,求解决方法
解决HTTP请求中阿拉伯文本显示异常的问题
以下是针对阿拉伯文本乱码问题的具体排查和解决步骤:
强制使用UTF-8解析响应内容
http包默认会根据响应头的Content-Type选择编码,但如果后端未正确设置charset,可能会用latin1解析非拉丁字符导致乱码。直接通过bodyBytes手动用UTF-8解码:Future<Iterable<SubCategories>> fetchCategories() async { final res = await http.post( Uri.parse('https://___________________'), ); // 替换原有的jsonDecode(res.body) final List<dynamic> responseJson = jsonDecode(utf8.decode(res.bodyBytes))["response"]; late Iterable<SubCategories> allCategories = responseJson .map((subCategoryJson) => SubCategories.fromJson(subCategoryJson)); return allCategories; }注:使用前需确保已导入
dart:convert包(你应该已导入,因为用到了jsonDecode)。确认请求头的正确配置
检查请求头是否明确指定需要UTF-8编码的响应,避免后端返回非标准编码内容:final res = await http.post( Uri.parse('https://___________________'), headers: { 'Accept': 'application/json; charset=utf-8', 'Accept-Charset': 'utf-8', // 如果是发送JSON数据,同步设置Content-Type // 'Content-Type': 'application/json; charset=utf-8', }, );检查模型类的字段解析逻辑
确保SubCategories类中存储阿拉伯文本的字段为String类型,且fromJson方法直接正确取值,无额外转码或截断操作:class SubCategories { final String arabicName; // 其他字段... SubCategories({required this.arabicName}); factory SubCategories.fromJson(Map<String, dynamic> json) { return SubCategories( arabicName: json['arabic_name'] as String, // 其他字段解析逻辑... ); } }验证后端响应编码
打印res.headers['content-type']查看后端返回的编码类型,若不是charset=utf-8,优先联系后端修改为UTF-8编码;若后端确实使用其他编码(如ISO-8859-6),则需用对应编码解析(比如latin1.decode(res.bodyBytes)),但更推荐统一使用UTF-8标准编码。
内容的提问来源于stack exchange,提问作者Ayz
相关产品推荐
相关产品推荐

