在Flutter
开发中有一个使用非常广泛的组件,它的作用是:
有效容纳一个子组件并且可以自定义样式的容器。
这篇博客主要分享容器组件的Container
的使用,希望对看文章的小伙伴有所帮助。
主要使用的场景:
- 设置宽高:
Flutter
中大部分组件不能设置宽高,需要依赖容器; - 添加背景颜色;
- 添加背影图像;
- 添加内外边距:padding和margin属性;
- 添加边框;
- 设置圆角;
- 设置child对齐:居中、居左、居右、居上、居下或偏移;
- 设置变换:旋转或变形。
简单示例代码
Container(
height: 300,
color: Colors.red,
padding: const EdgeInsets.all(10),
margin: const EdgeInsets.all(10),
alignment: Alignment.center,
child: const Text(
'使用Container组件',
style: TextStyle(color: Colors.white),
),
),
效果如下:
源码
Container({
Key? key,
this.alignment,
this.padding,
this.color,
this.decoration,
this.foregroundDecoration,
double? width,
double? height,
BoxConstraints? constraints,
this.margin,
this.transform,
this.transformAlignment,
this.child,
this.clipBehavior = Clip.none,
}) : assert(margin == null || margin.isNonNegative),
assert(padding == null || padding.isNonNegative),
assert(decoration == null || decoration.debugAssertIsValid()),
assert(constraints == null || constraints.debugAssertIsValid()),
assert(clipBehavior != null),
assert(decoration != null || clipBehavior == Clip.none),
assert(color == null || decoration == null,
'Cannot provide both a color and a decoration\n'
'To provide both, use "decoration: BoxDecoration(color: color)".',
),
constraints =
(width != null || height != null)
? constraints?.tighten(width: width, height: height)
?? BoxConstraints.tightFor(width: width, height: height)
: constraints,
super(key: key);
属性说明
这里针对源码做出相应的属性说明,熟悉控件的属性方便大家的使用。
属性名称 | 属性说明 |
---|---|
child | 子组件,可以不设置。 |
transform | 变换效果,比如翻转、旋转、变形等 |
margin | 外边距 |
padding | 内边距 |
width | 宽度 |
height | 高度 |
constraints | 大小范围约束,constraints有四个属性:minWidth、minHeight、maxWidth、maxHeight。 |
alignment | child对齐的属性,可以设置居中、居左、居右、居上、居下等等。 |
foregroundDecoration | 设置前景装饰 |
color | 背景色 |
完整的示例代码
以下的代码,可以直接复制到编译器去运行,方便小伙伴查看运行结果或者直接使用:
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key, required this.title}) : super(key: key);
final String title;
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
// Here we take the value from the MyHomePage object that was created by
// the App.build method, and use it to set our appbar title.
title: Text(widget.title),
),
body: Container(
height: 300,
color: Colors.red,
padding: const EdgeInsets.all(10),
margin: const EdgeInsets.all(10),
alignment: Alignment.center,
child: const Text(
'使用Container组件',
style: TextStyle(color: Colors.white),
),
),
);
}
}