学习笔记:
准备工作
先创建一个项目,写如下代码
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(primarySwatch: Colors.blue),
home: Scaffold(
appBar: AppBar(
title: const Text("Flutter Demo"),
),
body: MyHomePage(),
),
);
}
}
class MyHomePage extends StatelessWidget {
Widget build(BuildContext context) {
return Text("你好flutter");
}
}
1.使用Padding组件设置边距
class MyHomePage extends StatelessWidget {
Widget build(BuildContext context) {
return Padding(
padding: EdgeInsets.all(10),
child: Text("你好flutter"),
);
}
}
效果
之前通常都是用Container,的padding属性,设置边距。
那么为什么使用Padding控件呢?
因为Padding占用的内存更少,性能更好(如果你只想要一个Padding效果的话)。
2.线性布局Row、Column
2.1 先创建一个IconContainer
//自定义一个控件
//实现传参控制icon和颜色
class IconContainer extends StatelessWidget {
Color color; //构造成命名参数,写在构造函数参数大括号内
IconData iconData;
//Can't define a const constructor for a class with non-final fields.
//color必须初始化,在这里我们给设置一个默认值
IconContainer(this.iconData, {Key? key, this.color = Colors.white})
: super(key: key);
Widget build(BuildContext context) {
return Container(
alignment: Alignment.center,
width: 120,
height: 120,
color: color,
child: Icon(iconData),
);
}
}
重点看一下构造函数的传参。
可以看到Color color参数传递是放在大括号内的,
IconData iconData参数是放在大括号外的。
大括号内的参数,可传可不传,大括号外的,必须传。
在这里我们设计的是一个IconContainer,Icon必须传,color选择性传即可。
2.2使用Row组件,展示IconContainer
class MyHomePage extends StatelessWidget {
Widget build(BuildContext context) {
return Row(
children: [
IconContainer(Icons.reorder),
IconContainer(
Icons.g_translate,
color: Colors.purple,
),
IconContainer(
Icons.ac_unit,
color: Colors.blue,
),
],
);
}
}
效果
可以看到,三个IconContainer横向排列在一起了
太紧凑?
设置些边距
给Row设置mainAxisAlignment: MainAxisAlignment.spaceBetween
显示效果
还可以设置mainAxisAlignment: MainAxisAlignment.spaceEvenly
“Place the free space evenly between the children as well as before and after the first and last child.”
显示效果
2.3 Column组件
class MyHomePage extends StatelessWidget {
Widget build(BuildContext context) {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
IconContainer(Icons.reorder),
IconContainer(
Icons.g_translate,
color: Colors.purple,
),
IconContainer(
Icons.ac_unit,
color: Colors.blue,
),
],
);
}
}
展示效果
3.弹性布局组件Flex Expanded
class MyHomePage extends StatelessWidget {
Widget build(BuildContext context) {
return Row(
children: [
Expanded(
flex: 1,
child: IconContainer(
Icons.g_translate,
color: Colors.purple,
)),
Expanded(
flex: 2,
child: IconContainer(
Icons.ac_unit,
color: Colors.blue,
)),
],
);
}
}
显示效果
另一种写法
class MyHomePage extends StatelessWidget {
Widget build(BuildContext context) {
return Flex(
direction: Axis.horizontal,
children: [
Expanded(
flex: 1,
child: IconContainer(
Icons.g_translate,
color: Colors.purple,
)),
Expanded(
flex: 2,
child: IconContainer(
Icons.ac_unit,
color: Colors.blue,
)),
],
);
}
}
4.如何让控件充满屏幕
设置Container的width\height为double.infinite