Flutter封装一个通用的图片组件

124次阅读
没有评论

  1. 安装依赖https://pub.dev/documentation/flutter_advanced_networkimage_2

flutter_advanced_networkimage已经年久失修了,不兼容dart3,有开发者在flutter_advanced_networkimage的基础上继续维护,重新发包为:flutter_advanced_networkimage_2

flutter pub add flutter_advanced_networkimage_2

具体代码实现:

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

final networkUriReg = RegExp('^http');
final localUriReg = RegExp('^static');

class CommonImage extends StatelessWidget {
  final String src;
  final double? width;
  final double? height;
  final BoxFit? fit;

  const CommonImage(this.src, {super.key, this.width, this.height, this.fit});

  @override
  Widget build(BuildContext context) {
    if (networkUriReg.hasMatch(src)) {
      // return Image(
      //   width: width,
      //   height: height,
      //   fit: fit,
      //   image: AdvancedNetworkImage(
      //     src,
      //     useDiskCache: true,
      //     cacheRule: CacheRule(maxAge: Duration(days: 7)),
      //     timeoutDuration: Duration(seconds: 20),
      //   ),
      // );
      return CachedNetworkImage(imageUrl: src, width: width, height: height, fit: fit);
    }
    if (localUriReg.hasMatch(src)) {
      return Image.asset(src, width: width, height: height, fit: fit);
    }
    assert(false, '图片地址 src 不合法 !');
    return Container();
  }
}

正文完
 0
wujingquan
版权声明:本站原创文章,由 wujingquan 于2025-04-30发表,共计1078字。
转载说明:Unless otherwise specified, all articles are published by cc-4.0 protocol. Please indicate the source of reprint.
评论(没有评论)