Flutter加载远程图片如何实现缓存图片的功能 cached_network_image的使用

发布于 1周前 作者 itying888 最后一次编辑是 5天前 来自 分享

Flutter缓存图片可以使用cached_network_image这个插件

Flutter cached_network_image 用于显示来自互联网的图像并将其保存在缓存目录中。

cached_network_image基本用法

和其它组件类似,CachedNetworkImage组件提供了相关的属性来控制自己,下面是该组件中常用的属性:

imageUrl:该属性主要用来控制被加载的网络图片,它的值是一个图片网址; imageBuilder:该属性主要用来装饰被加载的图片,比如对图片进行缩放操作; errorWidget:该属性主要用来控制显示的错误提示图标或者文字; placeholder:该属性用来控制在加载网络图片之前显示的占位图片资源; fit:该属性主要用来控制图片如何适应其父容器,这个是图片类组件中最常用的属性; progressIndicatorBuilder:该属性用来显示图标加载进度,它是方法类型,进度值在方法参数中;

cached_network_image详细用法

1、安装下载依赖

dependencies:
  cached_network_image: ^3.3.1

2、使用

使用占位符:

CachedNetworkImage(
        imageUrl: "http://via.placeholder.com/350x150",
        placeholder: (context, url) => CircularProgressIndicator(),
        errorWidget: (context, url, error) => Icon(Icons.error),
     ),

或者带有进度指示器:

CachedNetworkImage(
       imageUrl: "http://via.placeholder.com/350x150",
       progressIndicatorBuilder: (context, url, downloadProgress) => 
               CircularProgressIndicator(value: downloadProgress.progress),
       errorWidget: (context, url, error) => Icon(Icons.error),
 ),

或者

Image(image: CachedNetworkImageProvider(url))

当您既想拥有占位符功能,又想让 imageprovider 在另一个小部件中使用时,您可以提供 imageBuilder:

CachedNetworkImage(
  imageUrl: "http://via.placeholder.com/200x150",
  imageBuilder: (context, imageProvider) => Container(
    decoration: BoxDecoration(
      image: DecorationImage(
          image: imageProvider,
          fit: BoxFit.cover,
          colorFilter:
              ColorFilter.mode(Colors.red, BlendMode.colorBurn)),
    ),
  ),
  placeholder: (context, url) => CircularProgressIndicator(),
  errorWidget: (context, url, error) => Icon(Icons.error),
),

Flutter加载远程图片如何实现缓存图片的功能 cached_network_image的使用完整代码

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

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

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

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

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

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            CachedNetworkImage(
              width: 300,
              height: 200,
              imageUrl:
                  "https://www.itying.com/images/202209/goods_img/1176_P_1663733333908.png",
              imageBuilder: (context, imageProvider) => Container(
                decoration: BoxDecoration(
                  image: DecorationImage(
                      image: imageProvider,
                      fit: BoxFit.cover,
                      colorFilter:
                          ColorFilter.mode(Colors.red, BlendMode.colorBurn)),
                ),
              ),
              placeholder: (context, url) => const Center(
                child: SizedBox(
                  width: 80,
                  height: 80,
                  child: CircularProgressIndicator(),
                ),
              ),
              errorWidget: (context, url, error) => Icon(Icons.error),
            ),
            const SizedBox(height: 20),
            const Image(
                image: CachedNetworkImageProvider(
                    "https://www.itying.com/images/202209/goods_img/1176_P_1663733333908.png")),
            const Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headlineMedium,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: const Icon(Icons.add),
      ),
    );
  }
}

回到顶部