首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >Flutter中常用布局组件

Flutter中常用布局组件

作者头像
贺公子之数据科学与艺术
发布2025-12-18 09:47:13
发布2025-12-18 09:47:13
1180
举报
单子Widget布局:Container、Padding与Center

Container是一个多功能容器,可以设置宽高、背景色、圆角边框等样式属性,同时支持内外边距和对齐方式。示例中展示了如何将文本包装在红色背景的Container内:

代码语言:javascript
复制
Container(
  child: Text('Container(容器)在UI框架中是一个很常见的概念,Flutter也不例外。'),
  padding: EdgeInsets.all(18.0),
  margin: EdgeInsets.all(44.0),
  width: 180.0,
  height:240,
  alignment: Alignment.center,
  decoration: BoxDecoration(
    color: Colors.red,
    borderRadius: BorderRadius.circular(10.0),
  ),
)

Padding专门用于设置子Widget的内边距,支持通过EdgeInsets灵活定义各方向间距:

代码语言:javascript
复制
Padding(
  padding: EdgeInsets.all(44.0),
  child: Text('Container(容器)在UI框架中是一个很常见的概念,Flutter也不例外。'),
);

Center用于将子Widget居中显示,通常需要父容器提供足够空间。示例展示了文本居中效果:

代码语言:javascript
复制
Scaffold(
  body: Center(child: Text("Hello"))
);
多子Widget布局:Row、Column与Expanded

Row和Column分别用于水平和垂直排列子Widget。Expanded可分配剩余空间。以下代码演示了Row和Column的用法:

代码语言:javascript
复制
Row(
  children: <Widget>[
    Container(color: Colors.yellow, width: 60, height: 80,),
    Container(color: Colors.red, width: 100, height: 180,),
    Container(color: Colors.black, width: 60, height: 80,),
    Container(color: Colors.green, width: 60, height: 80,),
  ],
);

Column(
  children: <Widget>[
    Container(color: Colors.yellow, width: 60, height: 80,),
    Container(color: Colors.red, width: 100, height: 180,),
    Container(color: Colors.black, width: 60, height: 80,),
    Container(color: Colors.green, width: 60, height: 80,),
  ],
);
层叠Widget布局:Stack与Positioned

Stack允许子Widget层叠显示,配合Positioned可精确控制位置。示例中展示了文本和图片的层叠效果:

代码语言:javascript
复制
Stack(
  children: <Widget>[
    Image.network('https://example.com/image.jpg'),
    Positioned(
      bottom: 10,
      right: 10,
      child: Text('Layer Text'),
    ),
  ],
);
布局实践建议

使用Container时注意其只能包含一个子Widget,多子场景需用Row/Column等包装后再放入。

Row/Column默认不会滚动,内容超出需配合SingleChildScrollView或ListView。

Expanded需作为Row/Column的直接子Widget使用,通过flex参数分配剩余空间比例。

Stack的定位依赖于父容器尺寸,需确保父容器提供足够空间。

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2025-12-15,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 单子Widget布局:Container、Padding与Center
  • 多子Widget布局:Row、Column与Expanded
  • 层叠Widget布局:Stack与Positioned
  • 布局实践建议
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档