16、Flutter Wrap组件 实现流布局

发布时间 2023-11-22 10:19:12作者: 鲤斌
Wrap可以实现流布局,单行的Wrap跟Row表现几乎一致,单列的Wrap则跟Column表现几乎一致。但
Row与Column都是单行单列的,Wrap则突破了这个限制,mainAxis上空间不足时,则向crossAxis上
去扩展显示。
 

Wrap组件的使用

//自定义按钮组件
class MyApp extends StatelessWidget {
  String text; //按钮文字
  void Function()? onPressed; //方法传参
  MyApp(this.text, {super.key, required this.onPressed}); //必须传入required

  @override
  Widget build(BuildContext context) {
    return ElevatedButton(
      style: ButtonStyle(
        backgroundColor:
            MaterialStateProperty.all(Color.fromARGB(255, 241, 223, 223)),
        foregroundColor: MaterialStateProperty.all(Colors.black45),
      ),
      onPressed: onPressed,
      child: Text(text),
    );
  }
}

class MyApp2 extends StatelessWidget {
  const MyApp2({super.key});
  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(10),
    child: Wrap(
      alignment: WrapAlignment.center, //主轴的对其方式 center居中  end据右
      spacing: 10, //X轴间距
      runSpacing: 5, //y轴间距
      direction: Axis.horizontal,   // horizontal水平(默认是水平)    vertical 垂直
      children: [
        MyApp(
          "第一级",
          onPressed: () {
            print("第一级按钮1");
          },
        ),
        MyApp("第2级11", onPressed: () {},),
        MyApp("第3级 DA ", onPressed: () {},),
        MyApp("第4级", onPressed: () {},),
        MyApp("第5级DF ", onPressed: () {},),
        MyApp("第6级", onPressed: () {},),
        MyApp("第7级DA ", onPressed: () {},),
        MyApp("第8级", onPressed: () {},),
        MyApp("第9级D A ", onPressed: () {},),
      ],
    ));
  }
}