Container布局在Flutter里大量使用,它是一个组合Widget,内部有绘制Widget、定位Widget和尺寸Widget。Container组件常用属性如下图:
下面是一个Container的示例:
- 在工程下新建一个images文件夹,并放入几张图片如下图:
- 打开 pubspec.yaml 配置文件添加images配置如下图:
- 接下来编写Container代码如下:
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Container 布局',
home: LayoutDemo(),
);
}
}
class LayoutDemo extends StatelessWidget {
@override
Widget build(BuildContext context) {
Widget container = Container(
decoration: BoxDecoration(color: Colors.grey),
child: Column(
children: <Widget>[
Expanded( // 防止内容溢出
child: new Container(
width: 150,
height: 150,
// 添加装饰效果
decoration: new BoxDecoration(
border: new Border.all(width: 10, color: Colors.blueGrey),
borderRadius:
const BorderRadius.all(const Radius.circular(8))),
margin: const EdgeInsets.all(4.0),
child: new Image.asset('images/1.jpg'),
),
),
Expanded(
child: new Container(
width: 150,
height: 150,
decoration: new BoxDecoration(
border: new Border.all(width: 10, color: Colors.blueGrey),
borderRadius:
const BorderRadius.all(const Radius.circular(8))),
margin: const EdgeInsets.all(4.0),
child: new Image.asset(
'images/2.jpg',
),
),
),
Expanded(
child: new Container(
width: 150,
height: 150,
decoration: new BoxDecoration(
border: new Border.all(width: 10, color: Colors.blueGrey),
borderRadius:
const BorderRadius.all(const Radius.circular(8))),
margin: const EdgeInsets.all(4.0),
child: new Image.asset('images/3.jpg'),
),
),
Expanded(
child: new Container(
width: 150,
height: 150,
decoration: new BoxDecoration(
border: new Border.all(width: 10, color: Colors.blueGrey),
borderRadius:
const BorderRadius.all(const Radius.circular(8))),
margin: const EdgeInsets.all(4.0),
child: new Image.asset('images/4.jpg'),
),
)
],
),
);
return new Scaffold(
appBar: AppBar(
title: Text('Container'),
),
body: container,
);
}
}
效果如下图所示: