Flutter图片缓存插件cache_image的使用
Flutter 图片缓存插件 cache_image 的使用
Flutter Cache Image
一个用于加载并缓存网络或 Firebase 存储图片的 Flutter 插件,并且在下载失败时支持重试机制。
此插件支持从标准的网络路径以及 Firebase 存储路径(gs
路径)下载图片。
图片将存储在应用的临时目录中。
使用方法
要使用此插件,首先在 pubspec.yaml
文件中添加 cache_image
和 firebase_storage
作为依赖项:
dependencies:
cache_image: "^1.0.5"
firebase_storage: "^10.0.0"
然后在 Dart 文件中导入 cache_image
:
import 'package:cache_image/cache_image.dart';
如果要支持 Firebase 存储,请下载生成的 google-services.json
文件并将其放置在 android/app
目录下。接下来,修改 android/build.gradle
文件和 android/app/build.gradle
文件以添加 Google 服务插件,具体操作可参考 Firebase 助手。
如何使用
CacheImage
可以与任何支持 ImageProvider
的小部件一起使用。以下是一些示例代码:
示例 1:加载 Firebase 存储中的图片
Image(
fit: BoxFit.cover,
image: CacheImage('gs://your-project.appspot.com/image.png'),
),
示例 2:加载网络图片并设置缓存时间
Image(
fit: BoxFit.cover,
image: CacheImage(
'https://hd.tudocdn.net/874944?w=646&h=284',
duration: Duration(seconds: 2), // 缓存有效时间
durationExpiration: Duration(seconds: 10), // 缓存过期时间
),
),
示例 3:结合 FadeInImage
使用
FadeInImage(
fit: BoxFit.cover,
placeholder: AssetImage('assets/placeholder.png'), // 占位符图片
image: CacheImage('gs://your-project.appspot.com/image.jpg'),
)
更多用法可以参考 example
目录中的完整示例应用。
完整示例代码
以下是完整的示例代码,展示如何在 Flutter 应用中使用 CacheImage
:
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:cache_image/cache_image.dart';
import 'package:path_provider/path_provider.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
[@override](/user/override)
Widget build(BuildContext context) {
SystemChrome.setPreferredOrientations([
DeviceOrientation.portraitUp,
DeviceOrientation.portraitDown,
]);
return MaterialApp(
title: 'Flutter Cache Image',
theme: ThemeData(primaryColor: Colors.white),
home: MyHomePage(title: 'Flutter Cache Image'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
[@override](/user/override)
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
void _refresh() {
getTemporaryDirectory().then((dir) {
dir.delete(recursive: true); // 清除缓存
});
setState(() {});
}
[@override](/user/override)
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.white,
title: Text(
widget.title,
style: TextStyle(color: Colors.black),
),
),
body: Column(
children: <Widget>[
Expanded(
child: Stack(
children: <Widget>[
Container(
height: MediaQuery.of(context).size.height,
child: FadeInImage(
fit: BoxFit.cover,
placeholder: AssetImage('assets/placeholder.png'),
image: CacheImage(
'gs://testing-9ea12.appspot.com/bake-1706051_1920.jpg',
),
),
),
Positioned(
top: 0,
right: 0,
child: Container(
margin: EdgeInsets.all(16.0),
padding: EdgeInsets.all(16.0),
decoration: BoxDecoration(
color: Colors.white,
boxShadow: [
BoxShadow(
color: Colors.black54,
blurRadius: 10.0,
spreadRadius: 1.0,
offset: Offset(2.0, 1.0),
),
],
borderRadius: BorderRadius.circular(16.0),
),
child: Text("Firebase Storage"),
),
),
],
),
),
Container(height: 4.0),
Expanded(
child: Stack(
children: <Widget>[
Container(
height: MediaQuery.of(context).size.height,
child: FadeInImage(
fit: BoxFit.cover,
placeholder: AssetImage('assets/placeholder.png'),
image: CacheImage(
'https://hd.tudocdn.net/874944?w=646&h=284',
duration: Duration(seconds: 2),
durationExpiration: Duration(seconds: 10),
),
),
),
Positioned(
top: 0,
right: 0,
child: Container(
margin: EdgeInsets.all(16.0),
padding: EdgeInsets.all(16.0),
decoration: BoxDecoration(
color: Colors.white,
boxShadow: [
BoxShadow(
color: Colors.black54,
blurRadius: 10.0,
spreadRadius: 1.0,
offset: Offset(2.0, 1.0),
),
],
borderRadius: BorderRadius.circular(16.0),
),
child: Text("Network"),
),
),
],
),
),
],
),
floatingActionButton: FloatingActionButton(
onPressed: _refresh,
backgroundColor: Theme.of(context).primaryColor,
child: Icon(Icons.refresh, color: Colors.black),
),
);
}
}
更多关于Flutter图片缓存插件cache_image的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter图片缓存插件cache_image的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
cache_image
是一个用于 Flutter 的图片缓存插件,它可以帮助你更高效地加载和缓存网络图片,从而提升应用的性能和用户体验。以下是如何使用 cache_image
插件的基本步骤:
1. 添加依赖
首先,你需要在 pubspec.yaml
文件中添加 cache_image
插件的依赖:
dependencies:
flutter:
sdk: flutter
cache_image: ^0.3.0 # 请检查最新版本
然后运行 flutter pub get
来安装依赖。
2. 导入包
在你的 Dart 文件中导入 cache_image
包:
import 'package:cache_image/cache_image.dart';
3. 使用 CacheImage
组件
CacheImage
是一个可以直接替换 Image.network
的组件,它会自动处理图片的缓存和加载。
CacheImage(
imageUrl: 'https://example.com/image.jpg',
placeholder: (context) => CircularProgressIndicator(), // 加载时的占位符
errorWidget: (context, error, stackTrace) => Icon(Icons.error), // 加载错误时的占位符
fit: BoxFit.cover, // 图片的填充方式
);
4. 使用 CachedNetworkImageProvider
如果你需要直接使用 ImageProvider
,可以使用 CachedNetworkImageProvider
:
Image(
image: CachedNetworkImageProvider('https://example.com/image.jpg'),
fit: BoxFit.cover,
);
5. 清除缓存
你可以手动清除缓存,例如在用户退出登录时:
CacheImage.clearCache();
6. 配置缓存大小
你可以配置缓存的大小,默认是 100MB:
CacheImage.configureCache(maxSize: 200 * 1024 * 1024); // 200MB
7. 其他功能
cache_image
还支持其他一些功能,例如自定义缓存路径、设置缓存有效期等。你可以查看插件的文档以获取更多信息。
示例代码
以下是一个完整的示例代码,展示了如何使用 CacheImage
组件:
import 'package:flutter/material.dart';
import 'package:cache_image/cache_image.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
[@override](/user/override)
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('CacheImage Example'),
),
body: Center(
child: CacheImage(
imageUrl: 'https://example.com/image.jpg',
placeholder: (context) => CircularProgressIndicator(),
errorWidget: (context, error, stackTrace) => Icon(Icons.error),
fit: BoxFit.cover,
),
),
),
);
}
}