Skip to main content

Wrap 组件

Wrap 可以实现流布局,单行的 WrapRow 表现几乎一致,单列的 Wrap 则跟 Column 表现几乎一致。但 RowColumn 都是单行单列的,Wrap 则突破了这个限制,mainAxis 上空间不足时,则向 crossAxis 上去扩展显示。

名称类型含义
directionAxis主轴的方向,默认水平
alignmentWrapAlignment主轴的对其方式
spacingint主轴方向上的间距
textDirection文本方向
verticalDirection[]定义了 children 摆放顺序,默认是 down,见 Flex 相关属性介绍。
runAlignmentWrapAlignmentrun 的对齐方式。run 可以理解为新的行或者列,如果是水平方向布局的话,run 可以理解为新的一行
runSpacingrun的间距

Wrap组件搜索页面布局

import 'package:flutter/material.dart';

void main() {
runApp(const MyApp());
}

class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
), // ThemeData
home: Scaffold(
appBar: AppBar(
title: const Text("Flutter App")
),
body: const LayoutDemo(),
), // Scaffold
); // MaterialApp
}
}

class LayoutDemo extends StatelessWidget {
const LayoutDemo({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.all(10),
child: ListView(
children: [
Row(
children: [
Text("热搜",
style: Theme.of(context).textTheme.headline6,
)
],
), // Row
const Divider(),
Wrap(
spacing: 10,
runSpacing: 12,
children: [
Button("女装", onPressed: () {}),
Button("笔记本", onPressed: () {}),
Button("玩具", onPressed: () {}),
Button("文学", onPressed: () {}),
Button("女装", onPressed: () {}),
Button("时尚", onPressed: () {}),
Button("女装", onPressed: () {}),
Button("女装", onPressed: () {}),
],
), // Wrap
const SizedBox(height: 10),
Row(
children: [
Text(
"历史记录",
style: Theme.of(context).textTheme.headline6,
)
],
), // Row
const Divider(),
Column(
children: const [
ListTile(
title: Text("女装"),
),
Divider(),
ListTile(
title: Text("时尚"),
),Divider(),
],
), // Column
const SizedBox(height: 40),
Padding(
padding: const EdgeInsets.all(20),
child: OutlinedButton.icon(
onPressed: () {},
style: ButtonStyle(
foregroundColor: MaterialStateProperty.all(Colors.black38)
),
icon: const Icon(Icons.delete),
label: const Text("清空历史记录")
), // child
) // Padding
]
),
);
}
}

class Button extends StatelessWidget {
String text;
void Function()? onPressed;
Button(this.text, {Key? key, required this.onPressed}) : super(key: key);
@override
Widget build(BuildContext context) {
return ElevatedButton(
onPressed: onPressed,
style: ButtonStyle(
backgroundColor: MaterialStateProperty.all(const Color.fromARGB(255, 236, 233, 233)),
foregroundColor: MaterialStateProperty.all(Colors.black45),
), // ButtonStyle
child: Text(text),
); // ElevatedButton
}
}