
一、插件介绍
cached_network_image 是一款功能强大的 Flutter 网络图片缓存库,专为解决网络图片加载慢、重复加载消耗流量等问题而设计。该库针对开源鸿蒙(OpenHarmony)平台进行了深度适配,能够在鸿蒙设备上高效地缓存和显示网络图片,提供流畅的用户体验。
核心功能特性:
-
智能图片缓存:
- 自动缓存已加载的网络图片
- 支持自定义缓存策略和缓存大小
- 优化的缓存机制,减少重复网络请求
-
丰富的显示功能:
- 支持基本图片显示、列表显示和网格显示
- 支持圆形图片、圆角图片和自定义形状图片
- 支持图片变换和颜色滤镜
-
完善的加载状态管理:
- 支持加载占位符(placeholder)
- 支持加载进度指示器
- 支持加载错误处理
- 支持模糊占位符(BlurHash)
-
鸿蒙平台适配:
- 兼容鸿蒙 Stage 模型项目结构
- 与鸿蒙文件系统无缝集成
- 针对鸿蒙设备性能进行了优化
二、使用步骤
1. 包的引入
由于该库针对鸿蒙平台进行了自定义适配,需要通过 Git 方式引入依赖。在项目的 pubspec.yaml 文件中添加以下配置:
yaml
dependencies:
flutter:
sdk: flutter
cached_network_image: 3.2.3
baseflow_plugin_template: 2.1.2
cupertino_icons: ^1.0.2
dependency_overrides:
path_provider:
git:
url: "https://gitcode.com/openharmony-tpc/flutter_packages.git"
path: "packages/path_provider/path_provider"
2. 基本配置
鸿蒙项目结构配置
确保你的鸿蒙项目遵循标准的 Stage 模型结构,并且已经正确配置了 Flutter 集成环境。重点检查以下文件:
ohos/entry/src/main/ets/plugins/GeneratedPluginRegistrant.ets:确保已正确注册 PathProvider 插件ohos/entry/src/main/module.json5:配置正确的模块信息
插件初始化
在应用启动时,cached_network_image 会自动初始化,无需额外的配置代码。
3. API 调用和使用示例
基本使用示例
创建一个简单的图片显示页面,展示 cached_network_image 的基本用法:
dart
import 'package:flutter/material.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter_blurhash/flutter_blurhash.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'CachedNetworkImage 鸿蒙示例',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const ImageDisplayPage(),
);
}
}
class ImageDisplayPage extends StatelessWidget {
const ImageDisplayPage({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('CachedNetworkImage 鸿蒙示例'),
),
body: SingleChildScrollView(
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
// 使用 BlurHash 作为占位符
SizedBox(
width: double.infinity,
height: 200,
child: CachedNetworkImage(
placeholder: (context, url) => const AspectRatio(
aspectRatio: 1.6,
child: BlurHash(hash: 'LEHV6nWB2yk8pyo0adR*.7kCMdnj'),
),
imageUrl: 'https://blurha.sh/assets/images/img1.jpg',
fit: BoxFit.cover,
),
),
const SizedBox(height: 20),
// 使用 CircularProgressIndicator 作为占位符
SizedBox(
width: 300,
height: 150,
child: CachedNetworkImage(
placeholder: (context, url) => const CircularProgressIndicator(),
imageUrl: 'https://via.placeholder.com/300x150',
),
),
const SizedBox(height: 20),
// 带加载进度的图片
SizedBox(
width: 300,
height: 200,
child: CachedNetworkImage(
progressIndicatorBuilder: (context, url, progress) => Center(
child: CircularProgressIndicator(
value: progress.progress,
),
),
imageUrl: 'https://images.unsplash.com/photo-1532264523420-881a47db012d?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9',
),
),
const SizedBox(height: 20),
// 自定义图片样式
SizedBox(
width: 300,
height: 150,
child: CachedNetworkImage(
imageUrl: 'https://via.placeholder.com/300x150',
imageBuilder: (context, imageProvider) => Container(
decoration: BoxDecoration(
image: DecorationImage(
image: imageProvider,
fit: BoxFit.cover,
colorFilter: const ColorFilter.mode(
Colors.red,
BlendMode.colorBurn,
),
),
),
),
placeholder: (context, url) => const CircularProgressIndicator(),
errorWidget: (context, url, error) => const Icon(Icons.error),
),
),
const SizedBox(height: 20),
// 圆形图片
CachedNetworkImage(
imageUrl: 'https://via.placeholder.com/200x200',
placeholder: (context, url) => const CircleAvatar(
backgroundColor: Colors.amber,
radius: 100,
),
imageBuilder: (context, image) => CircleAvatar(
backgroundImage: image,
radius: 100,
),
),
const SizedBox(height: 20),
// 错误处理示例
SizedBox(
width: 300,
height: 150,
child: CachedNetworkImage(
imageUrl: 'https://notAvalid.uri',
placeholder: (context, url) => const CircularProgressIndicator(),
errorWidget: (context, url, error) => const Icon(Icons.error, size: 50, color: Colors.red),
),
),
],
),
),
),
);
}
}
列表中使用示例
创建一个包含多张网络图片的列表:
dart
import 'package:flutter/material.dart';
import 'package:cached_network_image/cached_network_image.dart';
class ImageListPage extends StatelessWidget {
const ImageListPage({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('图片列表示例'),
),
body: ListView.builder(
itemBuilder: (BuildContext context, int index) => Card(
margin: const EdgeInsets.all(10),
child: Column(
children: <Widget>[
CachedNetworkImage(
imageUrl: 'https://loremflickr.com/320/240/music?lock=$index',
placeholder: (BuildContext context, String url) => Container(
width: 320,
height: 240,
color: Colors.grey[200],
child: const Center(
child: CircularProgressIndicator(),
),
),
errorWidget: (context, url, error) => Container(
width: 320,
height: 240,
color: Colors.grey[200],
child: const Center(
child: Icon(Icons.error, color: Colors.red),
),
),
fit: BoxFit.cover,
),
Padding(
padding: const EdgeInsets.all(10),
child: Text('图片 $index', style: const TextStyle(fontSize: 16)),
),
],
),
),
itemCount: 50,
),
);
}
}
网格中使用示例
创建一个图片网格布局:
dart
import 'package:flutter/material.dart';
import 'package:cached_network_image/cached_network_image.dart';
class ImageGridPage extends StatelessWidget {
const ImageGridPage({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('图片网格示例'),
),
body: GridView.builder(
padding: const EdgeInsets.all(10),
itemCount: 100,
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 3, // 每行3个图片
crossAxisSpacing: 10,
mainAxisSpacing: 10,
childAspectRatio: 1, // 宽高比为1:1
),
itemBuilder: (BuildContext context, int index) => CachedNetworkImage(
imageUrl: 'https://loremflickr.com/200/200/cat?lock=$index',
placeholder: (context, url) => Container(
color: Colors.grey[200],
child: const Center(
child: CircularProgressIndicator(),
),
),
errorWidget: (context, url, error) => Container(
color: Colors.grey[200],
child: const Center(
child: Icon(Icons.error, color: Colors.red),
),
),
fit: BoxFit.cover,
),
),
);
}
}
4. 高级配置
自定义缓存管理器
你可以根据需要自定义缓存管理器:
dart
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter_cache_manager/flutter_cache_manager.dart';
// 创建自定义缓存管理器
final customCacheManager = CacheManager(
Config(
'customCacheKey',
stalePeriod: const Duration(days: 7),
maxNrOfCacheObjects: 1000,
),
);
// 使用自定义缓存管理器
CachedNetworkImage(
imageUrl: 'https://via.placeholder.com/300x150',
cacheManager: customCacheManager,
placeholder: (context, url) => const CircularProgressIndicator(),
);
清除缓存
你可以根据需要清除图片缓存:
dart
// 清除特定图片的缓存
await DefaultCacheManager().removeFile('https://via.placeholder.com/300x150');
// 清除所有缓存
await DefaultCacheManager().emptyCache();
三、总结
cached_network_image 是一款功能强大的 Flutter 网络图片缓存库,通过鸿蒙化适配,能够在开源鸿蒙平台上高效地工作。该库提供了丰富的图片显示功能和完善的加载状态管理,能够帮助开发者轻松实现高质量的图片展示效果。
核心优势:
- 提高性能:通过缓存机制减少网络请求,提高图片加载速度
- 节省流量:避免重复下载相同的图片,节省用户流量
- 提升体验:提供流畅的加载动画和错误处理,提升用户体验
- 易于使用:简洁的 API 设计,方便开发者快速集成
- 鸿蒙适配:针对鸿蒙平台进行了深度优化,确保在鸿蒙设备上的最佳性能
使用 cached_network_image 可以显著提升你的鸿蒙应用中图片处理的效率和用户体验,是开发高质量鸿蒙应用的必备工具之一。
欢迎加入开源鸿蒙跨平台社区:https://openharmonycrossplatform.csdn.net