HarmonyOS 鸿蒙Next cached_network_image三方库的使用接入案例

发布于 1周前 作者 yuanlaile 来自 鸿蒙OS

HarmonyOS 鸿蒙Next cached_network_image三方库的使用接入案例 希望提供cached_network_image三方库的使用接入案例

2 回复

cached_network_image是纯dart库,可以直接使用 参考demo: pubspec.yaml:

name: flutter_dev11
description: A new Flutter project.
# The following line prevents the package from being accidentally published to
# pub.dev using `flutter pub publish`. This is preferred for private packages.
publish_to: 'none' # Remove this line if you wish to publish to pub.dev

The following defines the version and build number for your application.
A version number is three numbers separated by dots, like 1.2.43
followed by an optional build number separated by a +.
Both the version and the builder number may be overridden in flutter
build by specifying --build-name and --build-number, respectively.
In Android, build-name is used as versionName while build-number used as versionCode.
Read more about Android versioning at https://developer.android.com/studio/publish/versioning
In iOS, build-name is used as CFBundleShortVersionString while build-number is used as CFBundleVersion.
Read more about iOS versioning at
https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
In Windows, build-name is used as the major, minor, and patch parts
of the product and file versions while build-number is used as the build suffix.
version: 1.0.0+1
environment:
  sdk: '>=2.19.6 <3.0.0'
Dependencies specify other packages that your package needs in order to work.
To automatically upgrade your package dependencies to the latest versions
consider running flutter pub upgrade --major-versions. Alternatively,
dependencies can be manually updated by changing the version numbers below to
the latest version available on pub.dev. To see which dependencies have newer
versions available, run flutter pub outdated.
dependencies:
  flutter:
    sdk: flutter
The following adds the Cupertino Icons font to your application.
Use with the CupertinoIcons class for iOS style icons.
  cupertino_icons: ^1.0.2
  baseflow_plugin_template: ^2.1.2
  flutter_blurhash: ^0.7.0
  cached_network_image: 3.2.3
dev_dependencies:
  flutter_test:
    sdk: flutter
The "flutter_lints" package below contains a set of recommended lints to
encourage good coding practices. The lint set provided by the package is
activated in the analysis_options.yaml file located at the root of your
package. See that file for information about deactivating specific lint
rules and activating additional ones.
  flutter_lints: ^2.0.0
For information on the generic Dart part of this file, see the
following page: https://dart.dev/tools/pub/pubspec
The following section is specific to Flutter packages.
flutter:
The following line ensures that the Material Icons font is
included with your application, so that you can use the icons in
the material Icons class.
  uses-material-design: true
To add assets to your application, add an assets section, like this:
assets:
- images/a_dot_burr.jpeg
- images/a_dot_ham.jpeg
An image asset can refer to one or more resolution-specific "variants", see
https://flutter.dev/assets-and-images/#resolution-aware
For details regarding adding assets from package dependencies, see
https://flutter.dev/assets-and-images/#from-packages
To add custom fonts to your application, add a fonts section here,
in this "flutter" section. Each entry in this list should have a
"family" key with the font family name, and a "fonts" key with a
list giving the asset and other descriptors for the font. For
example:
fonts:
- family: Schyler
  fonts:
  - asset: fonts/Schyler-Regular.ttf
  - asset: fonts/Schyler-Italic.ttf
  style: italic
- family: Trajan Pro
  fonts:
  - asset: fonts/TrajanPro.ttf
  - asset: fonts/TrajanPro_Bold.ttf
  weight: 700

For details regarding fonts from package dependencies,
see https://flutter.dev/custom-fonts/#from-packages
import 'dart:io';

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

void main() {
  CachedNetworkImage.logLevel = CacheManagerLogLevel.debug;
  runApp(
    BaseflowPluginExample(
      pluginName: 'CachedNetworkImage',
      githubURL: 'https://github.com/Baseflow/flutter_cached_network_image',
      pubDevURL: 'https://pub.dev/packages/cached_network_image',
      pages: [
        BasicContent.createPage(),
        ListContent.createPage(),
        GridContent.createPage(),
      ],
    ),
  );
}

/// Demonstrates a [StatelessWidget] containing [CachedNetworkImage]
class BasicContent extends StatelessWidget {
  const BasicContent({super.key});

  static ExamplePage createPage() {
    return ExamplePage(Icons.image, (context) => const BasicContent());
  }

  @override
  Widget build(BuildContext context) {
    return SingleChildScrollView(
      child: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            _blurHashImage(),
            _sizedContainer(
              const Image(
                image: CachedNetworkImageProvider(
                  'https://via.placeholder.com/350x150',
                ),
              ),
            ),
            _sizedContainer(
              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',
              ),
            ),
            _sizedContainer(
              CachedNetworkImage(
                placeholder: (context, url) =>
                    const CircularProgressIndicator(),
                imageUrl: 'https://via.placeholder.com/200x150',
              ),
            ),
            _sizedContainer(
              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),
              ),
            ),
            CachedNetworkImage(
              imageUrl: 'https://via.placeholder.com/300x300',
              placeholder: (context, url) => const CircleAvatar(
                backgroundColor: Colors.amber,
                radius: 150,
              ),
              imageBuilder: (context, image) => CircleAvatar(
                backgroundImage: image,
                radius: 150,
              ),
            ),
            _sizedContainer(
              CachedNetworkImage(
                imageUrl: 'https://notAvalid.uri',
                placeholder: (context, url) =>
                    const CircularProgressIndicator(),
                errorWidget: (context, url, error) => const Icon(Icons.error),
              ),
            ),
            _sizedContainer(
              CachedNetworkImage(
                imageUrl: 'not a uri at all',
                placeholder: (context, url) =>
                    const CircularProgressIndicator(),
              ),
            ),
            _sizedContainer(
              CachedNetworkImage(
                maxHeightDiskCache: 10,
                imageUrl: 'https://via.placeholder.com/350x200',
                placeholder: (context, url) =>
                    const CircularProgressIndicator(),
                errorWidget: (context, url, error) => const Icon(Icons.error),
                fadeInDuration: const Duration(seconds: 3),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

Widget _blurHashImage() {
  return SizedBox(
    width: double.infinity,
    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,
    ),
  );
}

Widget _sizedContainer(Widget child) {
  return SizedBox(
    width: 300,
    height: 150,
    child: Center(child: child),
  );
}
/// Demonstrates a [ListView] containing [CachedNetworkImage]
class ListContent extends StatelessWidget {
  const ListContent({super.key});

  static ExamplePage createPage() {
    return ExamplePage(Icons.list, (context) => const ListContent());
  }

  @override
  Widget build(BuildContext context) {
    return ListView.builder(
      itemBuilder: (BuildContext context, int index) => Card(
        child: Column(
          children: [
            CachedNetworkImage(
              imageUrl: 'https://loremflickr.com/320/240/music?lock=$index',
              placeholder: (BuildContext context, String url) => Container(
                width: 320,
                height: 240,
                color: Colors.purple,
              ),
            ),
          ],
        ),
      ),
      itemCount: 250,
    );
  }
}
/// Demonstrates a [GridView] containing [CachedNetworkImage]
class GridContent extends StatelessWidget {
  const GridContent({super.key});

  static ExamplePage createPage() {
    return ExamplePage(Icons.grid_on, (context) => const GridContent());
  }

  @override
  Widget build(BuildContext context) {
    return GridView.builder(
      itemCount: 250,
      gridDelegate:
          const SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 3),
      itemBuilder: (BuildContext context, int index) => CachedNetworkImage(
        imageUrl: 'https://loremflickr.com/100/100/music?lock=$index',
        placeholder: _loader,
      ),
    );
  }

  Widget _loader(BuildContext context, String url) {
    return const Center(child: CircularProgressIndicator());
  }

  Widget _error(BuildContext context, String url, Object error) {
    return const Center(child: Icon(Icons.error));
  }
}

更多关于HarmonyOS 鸿蒙Next cached_network_image三方库的使用接入案例的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


使用接入cached_network_image三方库的案例

  1. 引入库: 确保你已经在项目中引入了cached_network_image库。这通常通过在build.gradle文件中添加依赖项来完成,但在鸿蒙系统中,可能需要通过鸿蒙的包管理工具进行依赖管理。

  2. 布局文件: 在XML布局文件中,添加一个支持网络图片加载的组件,比如Image组件,并设置相应的属性。

  3. 代码实现: 在对应的JavaScript(或其他鸿蒙支持的脚本语言)文件中,初始化cached_network_image库,并设置图片的URL。库会自动处理图片的下载、缓存和显示。

  4. 错误处理: 添加必要的错误处理逻辑,比如图片加载失败时的占位图显示。

  5. 运行测试: 运行应用,查看cached_network_image是否能够正确加载并显示网络图片。

如果在使用过程中遇到具体问题,比如图片无法加载、缓存失效等,请检查网络连接、图片URL的有效性以及库的版本兼容性。

如果问题依旧没法解决请联系官网客服, 官网地址是 https://www.itying.com/category-93-b0.html

回到顶部