在项目中比较经常会用到复用一个组件,比如上图中的示例,还有就是列表页的cell的展示等等,自定义组件分为三种:
1:组合现有组件
2:自绘
3:实现RenderObject
基本上如果没有特殊的UI,没有现有的Widget可以组装的话就只能用后两种了,大部分还是可以组合现有组件可以实现的。
以上面“我的房屋”item为例:
功能:上图下文、可点击、四周有阴影
实现:
import 'package:flutter/material.dart';
class ItemButton extends StatelessWidget {
ItemButton({//把需要在外面自己设置的值在这里定义一下,然后在下面的属性中使用这上面的变量
this.color,
this.borderRadius,
this.shadowColor,
this.boxwidth,
this.boxheight,
this.icon,
this.label,
this.onPressed,
});
final Color color;
final Color shadowColor;
final BorderRadiusGeometry borderRadius;
final double boxwidth;
final double boxheight;
final Icon icon;
final Text label;
final GestureTapCallback onPressed;
@override
Widget build(BuildContext context){
return GestureDetector(
onTap: onPressed,
child: Container(
decoration:BoxDecoration(
color: color,
borderRadius: borderRadius,
boxShadow: [
BoxShadow(
color: shadowColor,
offset: Offset(0.0,0.0),
blurRadius: 10.0,
spreadRadius: 2.0
)
],
),
width: boxwidth,
height: boxheight,
child:Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Padding(
padding: EdgeInsets.symmetric(vertical: 5),
child: icon
),
Padding(
padding: EdgeInsets.symmetric(vertical: 5),
child: label
)
],
)
),
);
}
}
//使用:把ItemButton看做一个普通的Widget使用就可以了,别忘了import ItemButton.dart',使用正确的路径。
ItemButton(
color: Colors.white,
borderRadius:BorderRadius.circular(8),
shadowColor: Colors.grey.shade50,
boxwidth: (MediaQuery.of(context).size.width - 50)/4,
boxheight: (MediaQuery.of(context).size.width - 50)*5/16,
icon: Icon(Icons.home,color: Colors.purpleAccent),
label: Text("我的房屋",textAlign:TextAlign.center),
onPressed: () => {
Navigator.push(context,
MaterialPageRoute(builder: (context){
return MyHouse();
})
)
},),
总结:其实也不难,就是刚开始的时候照葫芦画瓢就行了
1、里面一些变量类型要写对了,比如double类型的容易写成Double,这也是错误的
2、分号,逗号位置
3、自定义组件有个技巧就是可以先在外面自己写一个实例,配置好各个属性跑起来,满足自己需求的时候,然后新创建一个组件类,起个有辨识度的名字,然后把代码粘贴过来,看哪些属性需要外传,就把这个属性给摘出来定义一下就可以了
网友评论