紧接着上一篇完美封装Text,本次依然使用android的写法,封装Image,加载本地图片比较简单,这边主要加载网络图片,同步设置宽度、高度、圆角、圆形图片、边框宽度、边框颜色等参数
先看效果图
?
?依然还是熟悉的配方,依然还是熟悉的味道,让你写Flutter有写android组件的感觉
ImageView(
imageUrl,
width: 100,
height: 100,
marginLeft: 10,
cornerRadius: 5,
borderWidth: 2,
marginTop: 20,
isCircle: true,
borderColor: Colors.yellow,
)
封装的类我们依然使用ImageView,以下是源代码
import 'package:flutter/material.dart';
class ImageView extends StatelessWidget {
String url = "";
double? width = 0;
double? height = 0;
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;
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,
}) {
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;
}
}
}
@override
Widget build(BuildContext context) {
return Container(
width: width ?? 0,
height: height ?? 0,
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: ClipRRect(
borderRadius: BorderRadius.circular(this.cornerRadius ?? 0),
child: Image.network(
url,
width: this.width ?? 0,
height: this.height ?? 0,
fit: BoxFit.cover,
)));
}
}
这个美中不足的就是你需要设置宽度和高度,Flutter自适应的问题,我一直搞的不是很清楚,但大部分使用图片的场景都是需要设置宽高的,有些不需要设置宽高展示原本图片大小的,那就可以直接用原生的了,也很简单
|