Flutter图片缓存插件paulonia_cache_image的使用

Flutter图片缓存插件paulonia_cache_image的使用

Paulonia Cache Image 是一个用于下载和存储图片到缓存的Flutter插件。它支持Android、iOS和Web平台上的内存缓存和存储缓存,并且可以处理网络图片和Google Cloud Storage图片。

使用

要使用此插件,首先需要在 pubspec.yaml 文件中添加依赖:

dependencies:
  paulonia_cache_image: ^版本号

然后,在你的 main() 函数中初始化插件:

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await PCacheImage.init();
  runApp(MyApp());
}

init() 函数中,你可以设置 PCacheImage 的默认属性。例如,你可以更改所有 PCacheImage 小部件的值。

Paulonia cache image 扩展了 ImageProvider,因此你可以直接使用URL来加载图片。默认情况下,图片会被缓存到平台存储中:

Image(
  image: PCacheImage('https://i.imgur.com/jhRBVEp.jpg')
);

Image(
  image: PCacheImage(
    'gs://flutter-template-44674.appspot.com/images/user/0ooAw4dX5AeGhkH1JYkoWcdwvc72_big.jpg',
  )
);

内存缓存

默认的图像缓存存储在平台存储中有一个问题:当你调用 setState() 时,插件会从存储中读取并重新获取图片,这会导致图片闪烁。通过启用内存缓存,可以加快这一过程,并且不会出现闪烁。你可以在 PCacheImage 中启用内存缓存:

Image(
  image: PCacheImage('https://i.imgur.com/jhRBVEp.jpg', enableInMemory: true)
);

你也可以在 init() 函数中为所有 PCacheImage 小部件启用内存缓存:

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await PCacheImage.init(enableInMemory: true);
  runApp(MyApp());
}

但是,这种做法可能会增加内存使用量。我们建议仅在运行 setState() 的小部件中使用内存缓存以消除闪烁。为了避免内存无限制增长,你可以设置内存中最多可存储的图片数量:

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await PCacheImage.init(enableInMemory: true, maxInMemoryImages: 5);
  runApp(MyApp());
}

这个功能的工作原理类似于队列,当需要保存一张新图片时,最旧的一张图片将被删除。

清除整个缓存

有时你可能希望清除整个缓存,例如为了重建缓存。你可以通过以下方法清空缓存:

await PCacheImage.clearAllCacheImages();

CORS 在 Web 上

在Web上,当你尝试请求和下载图片时,可能会遇到CORS错误。根据图片类型,有相应的解决方案:

Google Storage 图片

你需要在你的桶中启用CORS配置:

参考


#### 网络图片

你可以在 `init()` 函数中设置代理:

```dart
void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await PCacheImage.init(proxy: "https://cors-anywhere.herokuapp.com/");
  runApp(MyApp());
}

proxy 属性仅在网络图片中使用,例如:“https://cors-anywhere.herokuapp.com/http://image.jpg”。

属性

PCacheImage 有以下属性:

属性 功能描述 默认值
enableInMemory 启用或禁用内存缓存 false
enableCache 启用或禁用缓存 true
retryDuration 如果下载失败,重试的持续时间 2秒
maxRetryDuration 重试累计的最大时间 10秒
imageScale 图片比例 1.0
maxInMemoryImages 设置内存中最多可存储的图片数量 7
clearCacheImage 从缓存中删除图片 false

作者

这个插件由 ChrisChV 开发,并在所有Paulonia项目中使用。

完整示例代码

以下是完整的示例代码,展示了如何使用 paulonia_cache_image 插件:

import 'package:flutter/material.dart';
import 'package:paulonia_cache_image/paulonia_cache_image.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await PCacheImage.init();
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Paulonia Cache Image',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: const MyHomePage(title: 'Paulonia Cache Image'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({required this.title, super.key});

  final String title;

  [@override](/user/override)
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  [@override](/user/override)
  void initState() {
    super.initState();
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.white,
        title: Text(
          widget.title,
          style: const TextStyle(color: Colors.black),
        ),
      ),
      floatingActionButton: FloatingActionButton(
        backgroundColor: Colors.white,
        onPressed: () {
          setState(() {});
        },
        child: const Icon(
          Icons.refresh,
          color: Colors.black,
        ),
      ),
      body: ListView(
        children: [
          const ListTile(
            title: Text('In memory cached network image'),
          ),
          SizedBox(
            height: 250,
            child: Card(
              elevation: 10,
              child: Image(
                image: PCacheImage(
                  'https://i.imgur.com/jhRBVEp.jpg',
                  enableInMemory: true,
                ),
              ),
            ),
          ),
          const ListTile(
            title: Text('Storage cached network image'),
          ),
          SizedBox(
            height: 250,
            child: Card(
              elevation: 10,
              child: Image(
                image: PCacheImage(
                  'https://i.imgur.com/5RhnXjE.jpg',
                ),
              ),
            ),
          ),
          const ListTile(
            title: Text('Not cached image'),
          ),
          SizedBox(
            height: 250,
            child: Card(
              elevation: 10,
              child: Image(
                image: PCacheImage(
                  'https://i.imgur.com/inAkwKw.jpg',
                  enableCache: false,
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }
}

更多关于Flutter图片缓存插件paulonia_cache_image的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter图片缓存插件paulonia_cache_image的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,下面是一个关于如何使用 paulonia_cache_image Flutter 插件来缓存图片的示例代码。这个插件可以帮助你高效地缓存和加载网络图片,从而提高应用的性能和用户体验。

首先,你需要在你的 pubspec.yaml 文件中添加 paulonia_cache_image 依赖:

dependencies:
  flutter:
    sdk: flutter
  paulonia_cache_image: ^最新版本号  # 请替换为最新版本号

然后运行 flutter pub get 来获取依赖。

接下来,你可以在你的 Flutter 应用中使用这个插件。以下是一个完整的示例代码,展示了如何使用 PauloniaCacheImage 来加载和缓存图片:

import 'package:flutter/material.dart';
import 'package:paulonia_cache_image/paulonia_cache_image.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'PauloniaCacheImage Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatelessWidget {
  final String imageUrl =
      'https://example.com/path/to/your/image.jpg';  // 替换为你的图片URL

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('PauloniaCacheImage Demo'),
      ),
      body: Center(
        child: PauloniaCacheImage(
          imageUrl: imageUrl,
          placeholder: (context, url) => CircularProgressIndicator(),
          errorWidget: (context, url, error) => Icon(Icons.error),
          fit: BoxFit.cover,
          width: 300,
          height: 300,
          // 其他可选参数
          // cacheKey: '自定义缓存键', // 如果你需要自定义缓存键
          // cacheDuration: Duration(days: 7), // 自定义缓存时间
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () async {
          // 清除缓存(可选)
          await PauloniaCacheImage.clearCache();
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(content: Text('缓存已清除')),
          );
        },
        tooltip: 'Clear Cache',
        child: Icon(Icons.delete),
      ),
    );
  }
}

代码说明:

  1. 依赖导入:在 pubspec.yaml 文件中添加 paulonia_cache_image 依赖。
  2. 构建应用:在 MyApp 中定义应用的基本结构。
  3. 展示图片:在 MyHomePage 中使用 PauloniaCacheImage 组件来加载和缓存图片。
    • imageUrl:图片的URL。
    • placeholder:加载图片时的占位符(这里使用了一个 CircularProgressIndicator)。
    • errorWidget:加载图片失败时显示的组件(这里使用了一个 Icon)。
    • fit:图片的缩放方式。
    • widthheight:图片的宽度和高度。
    • 其他可选参数如 cacheKeycacheDuration 可以根据需要进行自定义。
  4. 清除缓存:提供了一个浮动按钮来清除缓存,并显示一个SnackBar来确认操作。

这个示例展示了如何使用 paulonia_cache_image 插件来加载和缓存网络图片,并提供了清除缓存的功能。你可以根据自己的需求对代码进行进一步的修改和扩展。

回到顶部