给前端开发的一份 flutter 常用组件指南

本文为前端开发者提供了一份Flutter常用组件的详细指南,包括Container、SizedBox、Text、Image、Scaffold、LimitedBox、Row、Column等,解释了它们的用途、属性及示例,帮助开发者理解和应用这些组件进行界面构建和布局设计。
摘要由CSDN通过智能技术生成

Container

可以理解为div元素,可设置宽高等属性

常用属性如下:

属性类型描述
widthdouble
heightdouble
paddingEdgeInsetsGeometry内边距
marginEdgeInsetsGeometry外边距
colorColor背景色,注意不能跟decoration.color同时使用,会报错
decorationDecoration盒模型装饰器

示例:

Container(
    color: Colors.white,
    padding: EdgeInsets.only(top: 30),
    decoration: BoxDecoration(
        borderRadius: BorderRadius.all(Radius.circular(5)),
        border: Border(top: BorderSide(color: Colors.black,width: 1))
    )
)

等价于以下的样式:

<style>
  div {
    background-color: #fff;
    padding-top: 30px;
    border-radius: 5px;
    border-bottom: 1px solid #000;
  }
</style>

<div></div>

SizedBox

Container类似,但仅用于设置容器的宽高,如果需要设置背景色等,请使用Container

常用属性如下:

属性类型描述
widthdouble

示例:

SizedBox(
    height: 100
)

等价于以下的样式:

<style>
  div {
    height: 100px;
  }
</style>
<div></div>

Text

文本组件,用来显示文本的

常用属性如下:

属性类型描述
styleTextStyle文本相关样式,字体大小,加粗,颜色等
maxLinesint文本最大行数
overflowTextOverflow超出隐藏方式
textAlignTextAlign文本对齐方式

示例:

Text(
    '文本',
    maxLines: 2,
    overflow: TextOverflow.ellipsis,
    style: TextStyle(fontSize: 14, color: Colors.black87),
)

等价于以下的样式:

<style>
  div {
    word-break: break-all;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 2; /* 超出几行省略 */
    overflow: hidden;
  }
</style>

<div>文本</div>

Image

图片组件,可用于加载网络,手机,App 内的图片

加载网络图片

Image.network('xxx')

加载 App 内的图片

Image.asset('xxx')

加载手机图片

Image.file(file)

常用属性如下:

属性类型描述
widthdouble
heightdouble
fitBoxFit适配模式
alignmentAlignmentGeometry对齐方式

示例:

Image.network(
    'xxx',
    fit: BoxFit.contain,
    height: 88,
    width: 121,
    alignment: AlignmentDirectional.bottomEnd,
)

Scaffold

快速搭建页面框架的组件

常用属性如下:

属性类型描述
appBarPreferredSizeWidget顶部导航栏
bodyWidget内容区域
bottomNavigationBarWidget底部导航栏

示例:

Scaffold(
    appBar: AppBar(
        title: const Text('拍照功能'),
    ),
    body: PageView(),
      // 底部导航
    bottomNavigationBar: BottomNavigationBar(),
)

等价于以下的样式:

<style>
  .Scaffold {
    height: 100vh;
    display: flex;
    flex-direction: column;
  }
  .body {
    flex: 1;
  }
</style>
<div class="Scaffold">
  <div class="appBar">appBar</div>
  <div class="body">body</div>
  <div class="bottomNavigationBar">bottomNavigationBar</div>
</div>

LimitedBox

限制容器的最大宽高

常用属性如下:

属性类型描述
maxWidthdouble最大宽度
maxHeightdouble最大高度

示例:

LimitedBox(
    maxWidth: 130,
)

等价于以下的样式:

<style>
  div {
    max-width: 130px;
  }
</style>
<div></div>

Row

横向布局,css 中的 flex 布局

常用属性如下:

属性类型描述
mainAxisAlignmentMainAxisAlignment主轴对齐方式(水平方向)
crossAxisAlignmentCrossAxisAlignment副轴对齐方式(垂直方向)

示例:

Row(
  mainAxisAlignment: MainAxisAlignment.spaceAround,
  crossAxisAlignment: CrossAxisAlignment.center
)

等价于以下的样式:

<style>
  div {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
  }
</style>
<div></div>

Column

纵向布局,css 中的 flex 布局

常用属性如下:

属性类型描述
mainAxisAlignmentMainAxisAlignment主轴对齐方式(垂直方向)
crossAxisAlignmentCrossAxisAlignment副轴对齐方式(水平方向)

示例:

Column(
  mainAxisAlignment: MainAxisAlignment.spaceAround,
  crossAxisAlignment: CrossAxisAlignment.center
)

等价于以下的样式:

<style>
  div {
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    align-items: center;
  }
</style>
<div></div>

Expanded

Expanded必须要要结合Column或者Row一起使用,否则会报错。作用是动态调整 child 组件沿主轴的尺寸,比如填充剩余空间,比如设置尺寸比例。

常用属性如下:

属性类型描述
flexint占据剩余空间的比例

示例:

Row(
  children: [
    Expanded(child:Text('test'),flex:1),
    child:Text('test'),
  ],
)

等价于以下的样式:

<style>
  .row {
    display: flex;
    flex-direction: row;
  }
  .expanded {
    flex: 1;
  }
</style>
<div class="row">
  <div class="expanded"></div>
  <div></div>
</div>

Flexible

Flexible必须要要结合Column或者Row一起使用,Expanded组件就是继承于Flexible组件

常用属性如下:

属性类型描述
flexint填充比例
fitFlexFit可用空间填充方式

FlexFit.tight 被迫会将子类填充可用空间(1/6),所以设置后即使我们设置了子项宽度也没有作用

  • FlexFit.loose 允许子项 <= 可用空间
  • FlexFit.tight 子项 == 可用空间

示例:

Row(
  children: [
    Flexible(
      flex: 1
    ),
    Flexible(
      flex: 2
    ),
    Flexible(
      flex: 3
    ),
  ],
)

等价于以下的样式:

<style>
  .row {
    display: flex;
    flex-direction: row;
  }
  .flex-1 {
    flex: 1;
  }
  .flex-2 {
    flex: 2;
  }
  .flex-3 {
    flex: 3;
  }
</style>
<div class="row">
  <div class="flex-1"></div>
  <div class="flex-2"></div>
  <div class="flex-3"></div>
</div>

Card

Material风格的卡片控件,Card有较小的圆角和阴影。通常用于展示一组信息

常用属性如下:

属性类型描述
colorColor背景颜色
elevationdouble阴影值
shadowColorColor阴影颜色
shapeShapeBorder形状

示例:

Card(
  shadowColor: Colors.yellowAccent,
  shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(15)),
  //color: Colors.orange,
  elevation: 30
)

Stack

叠加布局组件,类似 css 中的绝对定位布局

示例:


Stack(
  children: [
    Text("aa"),
    Text("bb")
  ],
)

等价于以下的样式:

<style>
  .stack {
    position: relative;
  }
  .aa {
    position: absolute;
    top: 0;
    left: 0;
  }
  .bb {
    position: absolute;
    top: 0;
    left: 0;
  }
</style>
<div class="stack">
  <div class="aa">aa</div>
  <div class="bb">bb</div>
</div>

Positioned

绝对定位,一般跟Stack组件配合一起使用

Positioned.fill方法将填充 Stack 的整个空间

常用属性如下:

属性类型描述
leftdouble距离左边距离
topdouble距离上边距离
rightdouble距离右边距离
bottomdouble距离下边距离
widthdouble
heightdouble

示例:

Stack(
  children: [
    Positioned(
      left: 10,
      top: 10,
    )
  ],
)

等价于以下的样式:

<style>
  .stack {
    position: relative;
  }
  .flex-1 {
    position: absolute;
    top: 10px;
    left: 10px;
  }
</style>
<div class="stack">
  <div class="positioned"></div>
</div>

Padding

设置内边距

Icon

图标

常用属性如下:

属性类型描述
sizedouble图标大小
colorColor图标颜色

示例:

Icon(Icons.add,size: 10,color: Colors.black)

PhysicalModel

裁剪组件

场景:UI 需要实现四个角的圆角,常规是需要最外层容器设置borderRadius,然后里层的组件也需要设置borderRadius。通过PhysicalModel,只需要设置外层容器的borderRadius,里层组件会被自动裁剪。有点类似overflow:hiden

常用属性如下:

属性类型描述
shapeBoxShape设置裁剪形状
clipBehaviorClip设置裁剪行为
borderRadiusBorderRadius设置圆角半径
colorColor设置背景颜色

示例:

PhysicalModel(
  color: Colors.transparent,
  borderRadius: const BorderRadius.all(Radius.circular(6)),
  // 裁剪
  clipBehavior: Clip.antiAlias,
)

等价于以下的样式:

<style>
  .PhysicalModel {
    width: 100px;
    height: 100px;
    border-radius: 10px;
    background-color: red;
    /* 关键 */
    overflow: hidden;
  }

  .child {
    height: 100%;
    width: 100%;
    background-color: blue;
  }
</style>
<div class="PhysicalModel">
  <div class="child"></div>
</div>

ListView

滚动列表组件。涉及大量数据滚动使用ListView.builder可优化性能

示例:

ListView(
  children: [
    Text('text1'),
    Text('text2')
  ],
)

ListView.builder(
  itemCount: 3,
  itemBuilder: (BuildContext context, int index) {
    return Text('list');
  }
)

PageView

实现类似轮播图的效果

数据量大可通过PageView.builder优化性能

常用属性如下:

属性类型描述
scrollDirectionAxis滑动方向
physicsScrollPhysics滑动效果,NeverScrollableScrollPhysics禁用滑动
controllerPageController滚动控制器,可以定位页面,获取当前页面等信息

示例:

final PageController _controller = PageController(
      // 默认显示第几个页面
      initialPage: 0);
PageView(
  // 禁止左右滑动
  physics: NeverScrollableScrollPhysics(),
  controller: _controller,
  children: const [
    HomePage(),
    SearchPage(),
    TravelPage(),
    MyPage(),
  ],
);

PageView.builder(
  scrollDirection: Axis.vertical,
  itemCount: 3,
  itemBuilder: (context, index) {
    return Text('text')
  },
);

FractionallySizedBox

百分比布局

常用属性如下:

属性类型描述
widthFactordouble设置宽度比例
heightFactordouble设置高度比例

示例:

FractionallySizedBox(
  // 垂直占满
  heightFactor: 1,
)

等价于以下的样式:

<style>
  div {
    height: 100%;
  }
</style>
<div></div>

TabBar

一般配合TabBarView一起使用

常用属性如下:

属性类型描述
controllerTabController控制器
isScrollablebool多个标签时滚
indicatorColorColor标签指示器的颜色
labelColorColor标签的颜色
unselectedLabelColorColor未选中标签的颜色
indicatorSizeTabBarIndicatorSize指示器的大小
indicatorWeightdouble指示器的权重,即线条高度
tabsList<Widget>每个 tab 组件

示例见下文TabBarView组件配合一起使用

TabBarView

一般配合TabBar一起使用

常用属性如下:

属性类型描述
controllerTabController控制器

示例:

tip:类需要混入TickerProviderStateMixin

// with TickerProviderStateMixin
TravelTabModel? travelTabModel = TabController(length: tabs.length, vsync: this)

Column(
  children: [
    TabBar(
        controller: _controller,
        // 多个标签时滚动加载
        isScrollable: true,
        // 标签指示器的颜色
        indicatorColor: Colors.blue,
        // 标签的颜色
        labelColor: Colors.black,
        // 未选中标签的颜色
        unselectedLabelColor: Colors.black,
        // 指示器的大小
        indicatorSize: TabBarIndicatorSize.label,
        // 指示器的权重,即线条高度
        indicatorWeight: 4.0,
        tabs: tabs.map((e) => Tab(text: e.labelName ?? '')).toList()
    ),
    // Flexible组件可以使Row、Column、Flex等子组件在主轴方向有填充可用空间的能力,但是不强制子组件填充可用空间。
    // Expanded组件可以使Row、Column、Flex等子组件在其主轴方向上展开并填充可用空间,是强制子组件填充可用空间。
    // TabBarView需要明确一个高度
    Flexible(
        child: TabBarView(
            controller: _controller,
            children: tabs.map((e) => Text(e.labelName ?? '')).toList()))
  ],
)

Divider

分割线

常用属性如下:

属性类型描述
heightdouble高度
thicknessdouble线宽
indentdouble分割线左侧间距
endIndentdouble分割线右侧间距
colorColor分割线颜色

RefreshIndicator

实现下拉刷新

tip:实现上拉加载需要通过ScrollController监听滚动事件实现

常用属性如下:

属性类型描述
onRefreshFuture<void> Function()下拉回调方法
displacementdouble触发下拉刷新的距离
colorColor进度指示器前景色 默认为系统主题色
backgroundColorColor背景色

示例:

实现上拉加载和下拉刷新

ScrollController _scrollController = ScrollController();

void initState() {
  _scrollController.addListener(() {
    if (_scrollController.position.pixels ==
        _scrollController.position.maxScrollExtent) {
      // 上拉加载
    }
  });
}

RefreshIndicator(
  onRefresh: _handleRefresh,
)

GestureDetector

手势识别的组件,可以识别点击、双击、长按事件、拖动、缩放等手势

常用属性如下:

onTapDown 按下时回调

onTapUp 抬起时回调

onTap 点击事件回调

示例:

GestureDetector(
  onTap: () {},
)

RichText

富文本显示。结合TextSpan组件一起使用

常用属性如下:

属性类型描述
overflowTextOverflow对不可见文本操作
maxLinesint用来设置最大行数
textTextSpan必传参数,用来展示文本

示例:

RichText(
    text: TextSpan(children:
    [
  TextSpan(
      text: (searchItem.price ?? '') + ' ',
      style: TextStyle(fontSize: 16, color: Colors.orange)),
  TextSpan(
      text: ' ' + (searchItem.star ?? ''),
      style: TextStyle(fontSize: 12, color: Colors.grey))
  ])
  )

TextField

文本输入框

常用属性如下:

属性类型描述
controllerTextEditingController控制器
focusNodeFocusNode焦点
obscureTextbool是否隐藏文本,即显示密码类型
maxLinesint最多行数,高度与行数同步
autofocusint自动聚焦
decorationInputDecoration装饰
keyboardTypeTextInputType键盘类型,即输入类型
onChangedvoid Function(String)输入改变回
InputDecoration({
  this.icon,    //位于装饰器外部和输入框前面的图片
  this.labelText,  //用于描述输入框,例如这个输入框是用来输入用户名还是密码的,当输入框获取焦点时默认会浮动到上方,
  this.labelStyle,  // 控制labelText的样式,接收一个TextStyle类型的值
  this.helperText, //辅助文本,位于输入框下方,如果errorText不为空的话,则helperText不会显示
  this.helperStyle, //helperText的样式
  this.hintText,  //提示文本,位于输入框内部
  this.hintStyle, //hintText的样式
  this.hintMaxLines, //提示信息最大行数
  this.errorText,  //错误信息提示
  this.errorStyle, //errorText的样式
  this.errorMaxLines,   //errorText最大行数
  this.hasFloatingPlaceholder = true,  //labelText是否浮动,默认为true,修改为false则labelText在输入框获取焦点时不会浮动且不显示
  this.isDense,   //改变输入框是否为密集型,默认为false,修改为true时,图标及间距会变小
  this.contentPadding, //内间距
  this.prefixIcon,  //位于输入框内部起始位置的图标。
  this.prefix,   //预先填充的Widget,跟prefixText同时只能出现一个
  this.prefixText,  //预填充的文本,例如手机号前面预先加上区号等
  this.prefixStyle,  //prefixText的样式
  this.suffixIcon, //位于输入框后面的图片,例如一般输入框后面会有个眼睛,控制输入内容是否明文
  this.suffix,  //位于输入框尾部的控件,同样的不能和suffixText同时使用
  this.suffixText,//位于尾部的填充文字
  this.suffixStyle,  //suffixText的样式
  this.counter,//位于输入框右下方的小控件,不能和counterText同时使用
  this.counterText,//位于右下方显示的文本,常用于显示输入的字符数量
  this.counterStyle, //counterText的样式
  this.filled,  //如果为true,则输入使用fillColor指定的颜色填充
  this.fillColor,  //相当于输入框的背景颜色
  this.errorBorder,   //errorText不为空,输入框没有焦点时要显示的边框
  this.focusedBorder,  //输入框有焦点时的边框,如果errorText不为空的话,该属性无效
  this.focusedErrorBorder,  //errorText不为空时,输入框有焦点时的边框
  this.disabledBorder,  //输入框禁用时显示的边框,如果errorText不为空的话,该属性无效
  this.enabledBorder,  //输入框可用时显示的边框,如果errorText不为空的话,该属性无效
  this.border, //正常情况下的border
  this.enabled = true,  //输入框是否可用
  this.semanticCounterText,
  this.alignLabelWithHint,
})

示例:

TextField(
  autofocus: false,
  style: const TextStyle(
      fontSize: 18,
      color: Colors.black,
      fontWeight: FontWeight.w300),
  // 输入文本的样式
  decoration: InputDecoration(
      contentPadding: const EdgeInsets.fromLTRB(5, 0, 5, 0),
      // 去掉输入框底部线,修复设置了contentPadding后输入框内容不能垂直居中
      focusedBorder: const OutlineInputBorder(
          borderSide:
              BorderSide(width: 0, color: Colors.transparent)),
      disabledBorder: const OutlineInputBorder(
          borderSide:
              BorderSide(width: 0, color: Colors.transparent)),
      enabledBorder: const OutlineInputBorder(
          borderSide:
              BorderSide(width: 0, color: Colors.transparent)),
      border: InputBorder.none,
      hintText: widget.placeholder,
      hintStyle: const TextStyle(fontSize: 15)),
  controller: _controller,
  onChanged: _onChanged,
)

Button

  • FloatingActionButton:悬浮按钮
  • OutlineButton:带边框按钮
  • IconButton:图标按钮
  • BackButton:返回按钮
  • MaterialButton: Material 风格按钮

InkWell

作用跟GestureDetector类似。

GestureDetector 使用点击无水波纹出现,InkWell可以实现水波纹效果

ClipRRect

裁剪圆角

常用属性如下:

属性类型描述
borderRadiusBorderRadiusGeometry圆角大小

示例:

ClipRRect(
  borderRadius: const BorderRadius.all(Radius.circular(10))
);

BackdropFilter 和 ImageFilter

实现高斯模糊

示例:

BackdropFilter(
  filter: ImageFilter.blur(sigmaX: 10, sigmaY: 10),
  child: Container(
    color: Colors.white10,
    child: child,
  ),
)

CircularProgressIndicator

圆形指示器

常用属性:

属性类型描述
colorColor指示器颜色

示例:

CircularProgressIndicator(
  color: primary,
)

SingleChildScrollView

滚动组件,只能接受一个子组件

常用属性:

属性类型描述
controllerScrollController滚动控制器

示例:

ScrollController scrollController = ScrollController();

SingleChildScrollView(
  controller: scrollController,
)

NestedScrollView

嵌套滚动,滚动吸顶

常用属性:

属性类型描述
controllerScrollController滚动控制器
headerSliverBuilderList<Widget> Function头部(顶部)部分
bodyWidget内容部分,滚动部分

示例:

NestedScrollView(
  controller: controller,
  headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) {
    return [
      SliverAppBar(
        // 禁止出现appBar
        automaticallyImplyLeading: false,
//            扩展高度
        expandedHeight: 160,
//            标题栏是否固定
        pinned: true,
//            定义固定空间
        flexibleSpace: FlexibleSpaceBar(
          titlePadding: const EdgeInsets.only(left: 0),
          title: _buildHead(),
          // 背景
          background: Stack(
            children: [],
          ),
        ),
      )
    ];
  },
  body: ListView(),
)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值