紧接着上一篇完美封装Text,本次依然使用android的写法,封装Image,加载本地图片比较简单,这边主要加载网络图片,同步设置宽度、高度、圆角、圆形图片、边框宽度、边框颜色等参数
根据用户需求又更新了一版,保持原有功能不变的情况下新增以下内容
1.支持使用网络图片,本地图片,手机选取的图片,自动识别显示,通通只需要把string类型的url传入即可自动识别加载
2.加载网络图片使用第三方库cached_network_image,加载图片的时候缓存到本地,提升没有网络的时候和下一次再进入时候的加载时间
3.宽度和高度可以自己设置相应的宽度和高度,也可以不设置,不设置就自动显示图片原有的大小
第三方图片加载库版本:
cached_network_image: ^3.2.0
先看效果图
依然还是熟悉的配方,依然还是熟悉的味道,让你写Flutter有写android组件的感觉
ImageView(
imageUrl,
width: 100,
height: 100,
marginLeft: 10,
cornerRadius: 5,
borderWidth: 2,
marginTop: 20,
isCircle: true,
borderColor: Colors.yellow,
)
封装的类我们依然使用ImageView,以下是源代码
import 'dart:io';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
class ImageView extends StatelessWidget {
String url = "";
double? width;
double? height;
double? marginLeft = 0;
double? marginRight = 0;
double? marginTop = 0;
double? marginBottom = 0;
double? cornerRadius = 0;
double? margin = 0;
double? borderWidth = 0;
Color? borderColor = Colors.transparent;
bool? isCircle = false;
Color? backgroundColor = Colors.transparent;
VoidCallback? onClick;
ImageView(
this.url, {
this.width,
this.height,
this.marginBottom,
this.marginRight,
this.marginTop,
this.marginLeft,
this.margin,
this.cornerRadius,
this.isCircle,
this.borderColor,
this.borderWidth,
this.backgroundColor,
this.onClick,
}) {
if (margin != null) {
if (margin != null && margin! > 0) {
marginLeft = margin;
marginTop = margin;
marginRight = margin;
marginBottom = margin;
}
}
if (isCircle != null) {
if (isCircle ?? true) {
cornerRadius = width ?? 0 / 2;
}
}
if (onClick == Null) {
onClick = () {};
}
}
@override
Widget build(BuildContext context) {
return Container(
margin: EdgeInsets.fromLTRB(this.marginLeft ?? 0, this.marginTop ?? 0,
this.marginRight ?? 0, this.marginBottom ?? 0),
decoration: new BoxDecoration(
border: new Border.all(
width: this.borderWidth ?? 0,
color: this.borderColor ?? Colors.transparent),
color: this.backgroundColor,
borderRadius:
new BorderRadius.all(new Radius.circular(this.cornerRadius ?? 0)),
),
child: GestureDetector(
onTap: this.onClick,
child: ClipRRect(
borderRadius: BorderRadius.circular(this.cornerRadius ?? 0),
child: getImage()),
));
}
Widget getImage() {
if (url.startsWith("http")) {
//网络图片
return CachedNetworkImage(
imageUrl: url,
width: this.width,
height: this.height,
fit: BoxFit.cover,
);
} else if (url.startsWith("images")) {
//项目内图片
print("加载项目图片:${url}");
return Image.asset(url,
width: this.width,
height: this.height,
fit: BoxFit.cover);
} else {
//加载手机里面的图片
return Image.file(File(url),
width: this.width,
height: this.height,
fit: BoxFit.cover);
}
}
}