Flutter开发问题:无法通过Flagpedia API加载图片
问题描述
尝试从Flagpedia加载国旗图片,网站对应图片的HTML结构如下:
<img src="https://flagcdn.com/120x90/za.png" srcset="https://flagcdn.com/240x180/za.png 2x" width="120" height="90" alt="South Africa">
使用以下Flutter代码加载时出现错误:
Future<void> loadImage(String countryName) async { try { Response response = await get(Uri.parse('https://flagcdn.com/120x90/$countryName.png')); Map map = jsonDecode(response.body); name = map['alt']; //String image = map['src']; //String } catch (e) { if (kDebugMode) { print('could not get $countryName'); print(e); } } }
错误提示:
FormatException: SyntaxError: Unexpected token PNG
解决方法
核心问题是你请求的是PNG图片资源,却用jsonDecode解析响应体——https://flagcdn.com/120x90/za.png返回的是二进制图片文件,不是JSON数据,所以解析时会抛出格式错误。
根据你的需求分两种场景处理:
场景1:仅需显示国旗图片
直接用Flutter的Image.network组件加载即可,无需手动发请求解析:
Image.network( 'https://flagcdn.com/120x90/$countryCode.png', width: 120, height: 90, errorBuilder: (context, error, stackTrace) { // 加载失败时显示占位图标 return const Icon(Icons.error_outline); }, )
场景2:需要获取图片的alt文本(国家名称)
图片URL本身不返回alt信息,有两种解决方案:
方案一:本地维护映射表
提前创建国家代码与名称的对应字典,直接通过代码获取名称:final Map<String, String> countryMap = { 'za': 'South Africa', 'cn': 'China', 'us': 'United States', // 按需添加更多国家 }; // 使用时直接取值 name = countryMap[countryCode] ?? 'Unknown Country'; image = 'https://flagcdn.com/120x90/$countryCode.png';方案二:解析页面HTML获取
请求包含该国旗图片的页面,用html包解析HTML提取alt属性:- 先在
pubspec.yaml添加依赖:dependencies: html: ^0.15.4 - 编写解析代码:
import 'package:html/parser.dart' as parser; import 'package:html/dom.dart' as dom; import 'package:http/http.dart' as http; Future<void> loadImageInfo(String countryCode) async { try { // 请求对应国旗的详情页面(需确认Flagpedia的实际页面路径) final response = await http.get(Uri.parse('https://flagcdn.com/$countryCode.html')); final document = parser.parse(response.body); // 定位到目标img标签 final imgElement = document.querySelector('img[src*="$countryCode.png"]'); if (imgElement != null) { name = imgElement.attributes['alt'] ?? 'Unknown Country'; image = imgElement.attributes['src'] ?? ''; } } catch (e) { if (kDebugMode) { print('Failed to load info for $countryCode'); print(e); } } }
- 先在
内容的提问来源于stack exchange,提问作者Dufam
相关产品推荐
相关产品推荐

