这里写目录标题
1.自定义组件传参 字符串、方法
class HomePage extends StatelessWidget {
const HomePage({Key? key}) : super(key: key);
Widget build(BuildContext context) {
return Wrap(
children: [
MyButtonWidget('第一季', onclick: () {
print('1111');
}) // 组件传字符串和方法
],
);
}
}
// ignore: must_be_immutable
class MyButtonWidget extends StatelessWidget {
String title = ''; // 自定义组件接参字符串
void Function()? onclick; // 自定义组件接参方法
MyButtonWidget(this.title, {Key? key, required this.onclick})
: super(key: key); // 需要在构造函数声明,方便在 build 中使用;
Widget build(BuildContext context) {
return SizedBox(
child: ElevatedButton(
onPressed: onclick,
child: Text(title),
),
);
}
}
2.Wrap 组件使用
class HomePage extends StatelessWidget {
const HomePage({Key? key}) : super(key: key);
List<Widget> _initData() {
return lists.map((item) {
return MyButtonWidget(item["title"], onclick: () {});
}).toList();
}
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.all(16.0),
child: Wrap(
direction: Axis.vertical, // 垂直排布
// direction: Axis.horizontal, // 水平排布
spacing: 10, // 水平间距
runSpacing: 10, // 垂直间距
alignment: WrapAlignment.end, //居中对齐
children: _initData(),
),
);
}
}
// ignore: must_be_immutable
class MyButtonWidget extends StatelessWidget {
String title = ''; // 传参字符串
void Function()? onclick; // 传参是 fuction
MyButtonWidget(this.title, {Key? key, required this.onclick})
: super(key: key);
Widget build(BuildContext context) {
return SizedBox(
height: 36,
child: ElevatedButton(
style: ButtonStyle(
backgroundColor: MaterialStateProperty.all(
const Color.fromARGB(255, 235, 233, 233),
),
foregroundColor: MaterialStateProperty.all(
Colors.black54,
),
shadowColor: MaterialStateProperty.all(
Colors.black54.withOpacity(0.4),
),
),
onPressed: onclick,
child: Text(
title,
style: const TextStyle(
fontSize: 12,
),
),
),
);
}
}