Flutter中为CDN隐藏HTTPS的URL补全协议以加载图片
Flutter中为CDN隐藏协议的URL补全HTTPS协议以正常显示图片
完全可以在JSON模型映射阶段补全被CDN隐藏的HTTPS协议,核心思路是在模型的fromJson工厂方法中对图片URL做统一处理,以下是具体实现步骤:
1. 修改Article模型,添加URL补全逻辑
在模型中新增一个辅助方法处理URL协议补全,确保所有图片URL在映射时就被修正:
class Article{ final String? urlImage; final String? title; final String? description; Article({ required this.urlImage, required this.title, required this.description, }); // 辅助方法:补全URL协议 static String? completeImageUrl(String? url) { if (url == null) return null; // 处理CDN返回的//开头的相对协议URL if (url.startsWith('//')) { return 'https:$url'; } // 已有协议或其他合法URL直接返回 return url; } factory Article.fromJson(Map<String, dynamic> json) => Article( urlImage: completeImageUrl(json["_embedded"]["wp:featuredmedia"][0]["link"]), title: json["title"]["rendered"], description: json['content']['rendered'], ); Map<String, dynamic> toJson() { final Map<String, dynamic> data = <String, dynamic>{}; data['urlImage'] = urlImage; data['title'] = title; data['description'] = description; // 修正原拼写错误:desciption → description return data; } }
2. 优化API层,返回Article列表
将原始JSON数据直接转换为List<Article>,避免UI层重复处理原始数据:
class ApiNewsPage { String baseUrl = "https://www.assofacile.it/wp-json/wp/v2/posts?_embed"; Future<List<Article>> getNewsArticles() async { try { var response = await http.get(Uri.parse(baseUrl)); if (response.statusCode == 200) { List jsonList = jsonDecode(response.body); // 转换为Article模型列表 return jsonList.map((json) => Article.fromJson(json)).toList(); } else { throw Exception("Impossibile ricevere i dati, prova a controllare la connessione"); } } catch (SocketException) { throw Exception("Impossibile caricare gli articoli"); } } }
3. 更新UI代码,使用模型处理后的URL
UI层直接调用模型的urlImage字段,无需再处理原始JSON:
// 假设snapshot.data为List<Article>类型 SizedBox( height: 190, width: double.infinity, child: CachedNetworkImage( imageUrl: snapshot.data![i].urlImage ?? '', fit: BoxFit.cover, placeholder: (context, url) => Image.asset( "assets/gif/shimmer.gif", width: double.infinity, height: 190, fit: BoxFit.cover, ), errorWidget: (context, url, error) => Image.asset( "assets/images/unloadedImage.png", width: 250, height: 250, ), ), ),
关键说明
- 统一在模型层处理URL,避免在多个UI节点重复写补全逻辑,保证数据一致性
- 辅助方法兼容多种URL场景:空值、已有协议、相对协议的URL都能正确处理
- 修正了原模型
toJson方法中的拼写错误,避免后续序列化异常
内容的提问来源于stack exchange,提问作者Pimpi Rimpà
相关产品推荐
相关产品推荐

