import 'package:flutter/material.dart'; void main() { runApp(MyApp()); } class MyApp extends StatelessWidget { const MyApp({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter 盒子模型', theme: ThemeData( primarySwatch: Colors.blue, ), home: Scaffold( appBar: AppBar( title: const Text('盒子模型'), ), body: Center( child: Container( width: 300, height: 300, color: Colors.blue, // 背景色 child: Container( color: Colors.red, // 子盒子的背景色 margin: const EdgeInsets.fromLTRB(10, 0, 20, 30), // 子盒子的margin child: Container( margin: const EdgeInsets.symmetric( vertical: 50, horizontal: 50), // 子盒子的margin padding: const EdgeInsets.only(left: 20, right: 20), // 子盒子的padding color: Colors.white60, child: const Text( '这是一长段文字,这是一长段文字,这是一长段文字,这是一长段文字,这是一长段文字,这是一长段文字'), ), ), ), ), ), ); } }
Flutter 的盒子模型和 HTML 的是一样的,而通用的容器 Container 就相当于是一个通用的容器,和 HTML 的 div 标签一样。如果要控制一个元素的尺寸,外边距,内边距和边框,最通用的做法是使用 Container 容器将元素包裹。当然 Flutter 也提供了一些更为具体的布局组件方便开发,例如 :
- SizedBox:指定尺寸的容器。
- ConstraintedBox:带约束条件的容器,如限制最小最大宽度和高度。
- DecoratedBox:带装饰的容器,比如渐变色。
- RotatedBox:旋转一定角度的容器。
上面这些组件实际都可以通过 Container 的参数设置完成,只是开发的时候使用具体的容器可以减少组件参数。