flutter 之Wrap 组件及自定义组件传参 字符串、方法

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,
          ),
        ),
      ),
    );
  }
}

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值