flutter组件速查

Flutter 组件速查

本文档提供 Day2 课程中列出的组件的核心属性说明和最小可读示例(含注释)。只写核心内容,便于查阅和复制到项目中。

目录

  1. MaterialApp
  2. Scaffold
  3. 状态更新 – setState
  4. Container
  5. Center
  6. Align
  7. Padding
  8. Column
  9. Row
  10. Flex 和 Expanded
  11. Wrap
  12. Stack 和 Positioned
  13. Text
  14. Image
  15. TextField
  16. SingleChildScrollView
  17. ListView
  18. GridView
  19. CustomScrollView
  20. PageView

MaterialApp

说明:MaterialApp 是一个封装了 Material 风格应用的顶层容器,负责路由、主题、语言等全局配置。

属性:

  • key – Widget 的 key(Key)。
  • navigatorKey – 顶层导航钥匙(GlobalKey<NavigatorState>)。
  • scaffoldMessengerKey – ScaffoldMessenger 的 key(GlobalKey<ScaffoldMessengerState>)。
  • title – 应用标题(String)。
  • onGenerateTitle – 动态生成标题的回调(BuildContext -> String)。
  • color – 应用主题色(Color)。
  • theme – 主题配置(ThemeData)。
  • darkTheme – 暗色主题(ThemeData)。
  • themeMode – 主题模式(ThemeMode)。
  • locale – 当前本地化信息(Locale)。
  • localizationsDelegates – 本地化代理列表(LocalizationsDelegate 列表)。
  • supportedLocales – 支持的语言列表(List<Locale>)。
  • home – 应用的默认路由(Widget,通常为 Scaffold 或自定义页面)。
  • routes – 静态路由表(Map<String, WidgetBuilder>)。
  • initialRoute – 初始路由(String)。
  • onGenerateRoute – 动态路由生成器(RouteFactory)。
  • onUnknownRoute – 未知路由处理(RouteFactory)。
  • navigatorObservers – 导航观察者列表(List<NavigatorObserver>)。
  • builder – 构建顶层 Widget 的回调(WidgetBuilder)。
  • debugShowMaterialGrid – 是否显示网格(debug 用,bool)。
  • debugShowCheckedModeBanner – 是否显示 debug 横幅(bool)。
  • showPerformanceOverlay – 是否显示性能叠加(bool)。
  • checkerboardRasterCacheImages – 检查栅格缓存(bool)。
  • checkerboardOffscreenLayers – 检查离屏图层(bool)。
  • shortcuts – 快捷键映射(Map<LogicalKeySet, Intent>)。
  • actions – 动作映射(Map<Type, ActionFactory>)。

示例:

MaterialApp(
  title: 'Demo',
  theme: ThemeData(primarySwatch: Colors.blue),
  home: Scaffold(
    appBar: AppBar(title: Text('Home')),
    body: Center(child: Text('Hello MaterialApp')),
  ),
)

Scaffold

说明:Scaffold 提供了基本的 Material 页面结构:AppBarBodyDrawerFloatingActionButton 等。

属性:

  • key – Widget 的 key(Key)。
  • appBar – 顶部应用栏(通常为 AppBar)。
  • body – 页面主体(Widget)。
  • floatingActionButton – 悬浮按钮(FloatingActionButton)。
  • floatingActionButtonLocation – 悬浮按钮位置(FloatingActionButtonLocation)。
  • floatingActionButtonAnimator – 悬浮按钮动画器(FloatingActionButtonAnimator)。
  • persistentFooterButtons – 持续显示的底部按钮(List<Widget>)。
  • drawer – 抽屉(Drawer)。
  • endDrawer – 右侧抽屉(Drawer)。
  • bottomNavigationBar – 底部导航栏(Widget)。
  • bottomSheet – 底部弹出(Widget)。
  • backgroundColor – 背景色(Color)。
  • resizeToAvoidBottomInset – 键盘弹出时是否调整(bool)。
  • primary – 是否为主 Scaffolding(bool)。
  • drawerDragStartBehavior – 抽屉拖动行为(DragStartBehavior)。
  • extendBody – 是否扩展 body 到底部(bool)。
  • extendBodyBehindAppBar – 是否延伸到 appBar 后(bool)。

示例:

Scaffold(
  appBar: AppBar(title: Text('示例')),
  body: Center(child: Text('Scaffold Body')),
  floatingActionButton: FloatingActionButton(onPressed: () {}, child: Icon(Icons.add)),
)

状态更新 – setState

说明:setState 用于在 StatefulWidget 中更新状态并触发界面重建。

属性:

  • – 此为行为 API,属于 State 类的方法,用于触发重建。

示例:

class CounterWidget extends StatefulWidget {
  @override
  _CounterWidgetState createState() => _CounterWidgetState();
}

class _CounterWidgetState extends State<CounterWidget> {
  int _count = 0; // 内部状态

  void _increment() {
    setState(() {
      // 在这里修改状态,框架会重新调用 build
      _count++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Text('count: \\$_count'),
        ElevatedButton(onPressed: _increment, child: Text('Increment')),
      ],
    );
  }
}

Container

说明:Container 是通用容器,可设置尺寸、边距、内边距、背景、边框、对齐等。

属性:

  • key – Widget 的 key(Key)。
  • alignment – 子组件对齐方式(Alignment)。
  • padding – 内边距(EdgeInsets)。
  • color – 背景色(Color,只有当 decoration 为 null 时生效)。
  • decoration – 装饰(Decoration,例如 BoxDecoration,可设置 color、borderRadius、border 等)。
  • foregroundDecoration – 前景装饰(Decoration)。
  • width – 宽度(double)。
  • height – 高度(double)。
  • constraints – 大小约束(BoxConstraints)。
  • margin – 外边距(EdgeInsets)。
  • transform – 变换矩阵(Matrix4)。
  • transformAlignment – 变换对齐点(Alignment)。
  • clipBehavior – 裁剪行为(Clip)。

示例:

Container(
  width: 200,
  height: 100,
  padding: EdgeInsets.all(12), // 内边距
  margin: EdgeInsets.symmetric(vertical: 8), // 外边距
  alignment: Alignment.center,
  decoration: BoxDecoration(
    color: Colors.blue,
    borderRadius: BorderRadius.circular(8),
    border: Border.all(color: Colors.black12),
  ),
  child: Text('Container 示例', style: TextStyle(color: Colors.white)),
)

Center

说明:Center 将子组件在父布局中居中。

属性:

  • key – Widget 的 key(Key)。
  • widthFactor – 宽度因子(double,可用于对子项宽度进行缩放)。
  • heightFactor – 高度因子(double)。
  • child – 子组件(Widget)。

示例:

Center(
  child: Text('居中'),
)

Align

说明:Align 用来更精细地对齐子组件,支持 alignment 和尺寸因子。

属性:

  • key – Widget 的 key(Key)。
  • alignment – 对齐方式(Alignment, 如 Alignment.topRight)。
  • widthFactor – 宽度因子(double,可用于对子项宽度进行缩放)。
  • heightFactor – 高度因子(double)。
  • child – 子组件(Widget)。

示例:

Align(
  alignment: Alignment.topRight,
  child: Icon(Icons.star),
)

Padding

说明:Padding 用于给子组件添加内边距。

属性:

  • key – Widget 的 key(Key)。
  • padding – 内边距(EdgeInsets)。
  • child – 子组件(Widget)。

示例:

Padding(
  padding: EdgeInsets.fromLTRB(8, 16, 8, 16),
  child: Text('有内边距'),
)

Column

说明:Column 用于垂直布局,按列排列子项。

属性:

  • key – Widget 的 key(Key)。
  • children – 子组件列表(List<Widget>)。
  • mainAxisAlignment – 主轴对齐(MainAxisAlignment,例如 center)。
  • crossAxisAlignment – 交叉轴对齐(CrossAxisAlignment,例如 start)。
  • mainAxisSize – 主轴尺寸(MainAxisSize,min 或 max)。
  • textDirection – 文本方向(TextDirection)。
  • verticalDirection – 垂直方向(VerticalDirection)。
  • textBaseline – 文本基线(TextBaseline,用于对齐)。

示例:

Column(
  mainAxisAlignment: MainAxisAlignment.center,
  crossAxisAlignment: CrossAxisAlignment.start,
  children: [
    Text('第一行'),
    Text('第二行'),
  ],
)

Row

说明:Row 用于水平布局,按行排列子项。

属性:

  • key – Widget 的 key(Key)。
  • children – 子组件列表(List<Widget>)。
  • mainAxisAlignment – 主轴对齐(MainAxisAlignment,例如 spaceBetween)。
  • crossAxisAlignment – 交叉轴对齐(CrossAxisAlignment)。
  • mainAxisSize – 主轴尺寸(MainAxisSize)。
  • textDirection – 文本方向(TextDirection)。
  • verticalDirection – 垂直方向(VerticalDirection)。
  • textBaseline – 文本基线(TextBaseline)。

示例:

Row(
  mainAxisAlignment: MainAxisAlignment.spaceBetween,
  children: [
    Icon(Icons.menu),
    Text('标题'),
    Icon(Icons.search),
  ],
)

Flex 和 Expanded

说明:FlexRow/Column 的底层抽象,Expanded 用来在主轴上扩展占用剩余空间。

属性:

  • key – Widget 的 key(Key)。
  • flex – 权重(int,常用于 Expanded 或 Flexible)。
  • fit – 适配方式(FlexFit)。

示例:

Row(
  children: [
    Expanded(
      flex: 1, // 占 1 份
      child: Container(color: Colors.red, height: 50),
    ),
    Expanded(
      flex: 2, // 占 2 份
      child: Container(color: Colors.green, height: 50),
    ),
  ],
)

Wrap

说明:Wrap 是换行布局,超出会换行,类似 CSS 的 flex-wrap。

属性:

  • key – Widget 的 key(Key)。
  • direction – 方向(Axis.horizontal/vertical)。
  • alignment – 对齐(WrapAlignment)。
  • spacing – 子项间水平间距(double)。
  • runSpacing – 行间距(double)。
  • runAlignment – 行对齐(WrapAlignment)。
  • crossAxisAlignment – 交叉轴对齐(WrapCrossAlignment)。
  • textDirection – 文本方向(TextDirection)。
  • verticalDirection – 垂直方向(VerticalDirection)。
  • clipBehavior – 裁剪行为(Clip)。

示例:

Wrap(
  spacing: 8,
  runSpacing: 4,
  children: List.generate(8, (i) => Chip(label: Text('项 \\$i'))),
)

Stack 和 Positioned

说明:Stack 用于叠放布局,配合 Positioned 可做绝对定位。

属性:

  • key – Widget 的 key(Key)。
  • alignment – 对齐方式(Alignment)。
  • textDirection – 文本方向(TextDirection)。
  • fit – 适配方式(StackFit)。
  • clipBehavior – 裁剪行为(Clip)。
  • children – 子组件列表(List<Widget>)。

Positioned 属性:

  • key – Widget 的 key(Key)。
  • left – 距父容器左边距离(double)。
  • top – 距父容器顶部距离(double)。
  • right – 距父容器右边距离(double)。
  • bottom – 距父容器底部距离(double)。
  • width – 固定宽度(double)。
  • height – 固定高度(double)。

示例:

Stack(
  children: [
    Image.asset('assets/bg.png'),
    Positioned(
      bottom: 10,
      right: 10,
      child: FloatingActionButton(onPressed: () {}, child: Icon(Icons.add)),
    ),
  ],
)

Text

说明:Text 用于显示文本,支持样式与溢出处理。

属性:

  • key – Widget 的 key(Key)。
  • data – 文本内容(String,通常为第一个位置参数)。
  • style – 文本样式(TextStyle)。
  • strutStyle – 文本支撑样式(StrutStyle)。
  • textAlign – 对齐(TextAlign)。
  • textDirection – 文本方向(TextDirection)。
  • locale – 文本语言(Locale)。
  • softWrap – 是否软换行(bool)。
  • overflow – 溢出处理(TextOverflow,例如 ellipsis)。
  • textScaleFactor – 缩放因子(double)。
  • maxLines – 最大行数(int)。
  • semanticsLabel – 语义标签(String)。
  • textWidthBasis – 文本宽度基准(TextWidthBasis)。
  • textHeightBehavior – 文本高度行为(TextHeightBehavior)。

示例:

Text(
  '这是一个很长的文本示例,用于展示 ellipsis 溢出',
  maxLines: 1,
  overflow: TextOverflow.ellipsis,
  style: TextStyle(fontSize: 16, color: Colors.black87),
)

Image

说明:Image 系列用于加载图片(asset/network/file)。

属性:

  • key – Widget 的 key(Key)。
  • image – 图片提供者(ImageProvider,如 AssetImage/NetworkImage)。
  • frameBuilder – 帧构建器(FrameBuilder)。
  • loadingBuilder – 加载构建器(LoadingBuilder)。
  • errorBuilder – 错误回调(ImageErrorWidgetBuilder)。
  • semanticLabel – 语义标签(String)。
  • excludeFromSemantics – 是否从语义树中排除(bool)。
  • width – 宽度(double)。
  • height – 高度(double)。
  • color – 颜色混合(Color)。
  • colorBlendMode – 颜色混合模式(BlendMode)。
  • fit – 填充方式(BoxFit)。
  • alignment – 对齐方式(Alignment)。
  • repeat – 重复方式(ImageRepeat)。
  • centerSlice – 中心切片(Rect)。
  • matchTextDirection – 是否根据文本方向翻转(bool)。
  • gaplessPlayback – 无缝播放(bool)。
  • isAntiAlias – 抗锯齿(bool)。
  • filterQuality – 过滤质量(FilterQuality)。

示例:

Image.network(
  'https://example.com/image.jpg',
  width: 200,
  height: 120,
  fit: BoxFit.cover,
)

TextField

说明:TextField 是文本输入框,通常配合 TextEditingController 使用。

属性:

  • key – Widget 的 key(Key)。
  • controller – 文本控制器(TextEditingController)。
  • focusNode – 焦点节点(FocusNode)。
  • decoration – 输入装饰(InputDecoration,例如 labelText、hintText、border)。
  • keyboardType – 键盘类型(TextInputType)。
  • textInputAction – 输入动作(TextInputAction)。
  • textCapitalization – 自动大写(TextCapitalization)。
  • style – 文本样式(TextStyle)。
  • strutStyle – StrutStyle。
  • textAlign – 文本对齐(TextAlign)。
  • textAlignVertical – 文本垂直对齐(TextAlignVertical)。
  • autofocus – 自动获得焦点(bool)。
  • readOnly – 只读(bool)。
  • toolbarOptions – 工具栏选项(ToolbarOptions)。
  • showCursor – 是否显示光标(bool)。
  • obscureText – 密文(bool)。
  • autocorrect – 自动更正(bool)。
  • enableSuggestions – 启用建议(bool)。
  • maxLines – 最大行数(int)。
  • minLines – 最小行数(int)。
  • expands – 是否展开填满(bool)。
  • maxLength – 最大长度(int)。
  • onChanged – 文本变化回调(ValueChanged<String>)。
  • onEditingComplete – 编辑完成回调(VoidCallback)。
  • onSubmitted – 提交回调(ValueChanged<String>)。
  • inputFormatters – 输入格式化(List<TextInputFormatter>)。
  • enabled – 是否启用(bool)。
  • cursorWidth – 光标宽度(double)。
  • cursorHeight – 光标高度(double)。

示例:

final controller = TextEditingController();

TextField(
  controller: controller,
  decoration: InputDecoration(
    labelText: '用户名',
    hintText: '请输入用户名',
    border: OutlineInputBorder(),
  ),
)

SingleChildScrollView

说明:SingleChildScrollView 适用于只有一个子元素但需要滚动的场景。

属性:

  • key – Widget 的 key(Key)。
  • scrollDirection – 滚动方向(Axis)。
  • reverse – 是否反向(bool)。
  • padding – 内边距(EdgeInsets)。
  • primary – 是否作为主滚动视图(bool)。
  • physics – 滚动物理(ScrollPhysics)。
  • controller – 滚动控制器(ScrollController)。
  • clipBehavior – 裁剪行为(Clip)。
  • child – 子组件(通常为 Column)。

示例:

SingleChildScrollView(
  child: Column(
    children: List.generate(20, (i) => ListTile(title: Text('条目 \\$i'))),
  ),
)

ListView

说明:ListView 是常用滚动列表,ListView.builder 更高效用于大量子项。

属性:

  • key – Widget 的 key(Key)。
  • scrollDirection – 滚动方向(Axis)。
  • reverse – 是否反向(bool)。
  • controller – 滚动控制器(ScrollController)。
  • primary – 是否作为主滚动视图(bool)。
  • physics – 滚动物理(ScrollPhysics)。
  • shrinkWrap – 是否包裹内容(bool)。
  • padding – 内边距(EdgeInsets)。
  • itemExtent – 固定子项高度(double)。
  • prototypeItem – 原型子项(Widget,用于测量)。
  • cacheExtent – 缓存范围(double)。
  • itemCount – 项目数量(int,builder 模式)。
  • itemBuilder – 构建子项的回调(IndexedWidgetBuilder)。
  • separatorBuilder – 分隔构建器(ListView.separated)。
  • addAutomaticKeepAlives – 自动保持(bool)。
  • addRepaintBoundaries – 重绘边界(bool)。
  • addSemanticIndexes – 语义索引(bool)。
  • semanticChildCount – 语义子项计数(int)。
  • dragStartBehavior – 拖动起始行为(DragStartBehavior)。
  • keyboardDismissBehavior – 键盘隐藏行为(ScrollViewKeyboardDismissBehavior)。
  • restorationId – 恢复 ID(String)。
  • clipBehavior – 裁剪行为(Clip)。

示例:

ListView.builder(
  itemCount: items.length,
  itemBuilder: (context, index) {
    return ListTile(title: Text(items[index]));
  },
)

GridView

说明:GridView 用于网格布局,可通过 GridView.countGridView.builder 创建。

属性:

  • key – Widget 的 key(Key)。
  • scrollDirection – 滚动方向(Axis)。
  • reverse – 是否反向(bool)。
  • controller – 滚动控制器(ScrollController)。
  • primary – 是否作为主滚动视图(bool)。
  • physics – 滚动物理(ScrollPhysics)。
  • shrinkWrap – 是否包裹内容(bool)。
  • padding – 内边距(EdgeInsets)。
  • gridDelegate – 网格委托(SliverGridDelegate,例如 SliverGridDelegateWithFixedCrossAxisCount)。
  • children – 子组件列表(List<Widget>)。
  • cacheExtent – 缓存范围(double)。
  • semanticChildCount – 语义子项计数(int)。
  • dragStartBehavior – 拖动起始行为(DragStartBehavior)。
  • keyboardDismissBehavior – 键盘隐藏行为(ScrollViewKeyboardDismissBehavior)。
  • restorationId – 恢复 ID(String)。
  • clipBehavior – 裁剪行为(Clip)。

示例:

GridView.count(
  crossAxisCount: 3, // 3 列
  crossAxisSpacing: 8,
  mainAxisSpacing: 8,
  children: List.generate(9, (i) => Container(color: Colors.blueAccent)),
)

CustomScrollView

说明:CustomScrollView 可组合多个 sliver,实现复杂的滚动效果(如粘性标题、伸缩 appbar 等)。

属性(常见 Sliver):

  • key – Widget 的 key(Key)。
  • scrollDirection – 滚动方向(Axis)。
  • reverse – 是否反向(bool)。
  • controller – 滚动控制器(ScrollController)。
  • primary – 是否作为主滚动视图(bool)。
  • physics – 滚动物理(ScrollPhysics)。
  • shrinkWrap – 是否包裹内容(bool)。
  • center – 滚动中心(Key)。
  • anchor – 锚点(double)。
  • cacheExtent – 缓存范围(double)。
  • restorationId – 恢复 ID(String)。
  • clipBehavior – 裁剪行为(Clip)。
  • SliverAppBar – 可伸缩的 app bar(属性如 pinned、expandedHeight)。
  • SliverList – 列表的 sliver 版本(使用 SliverChildDelegate)。
  • SliverGrid – 网格的 sliver 版本。

示例:

CustomScrollView(
  slivers: [
    SliverAppBar(title: Text('标题'), pinned: true),
    SliverList(
      delegate: SliverChildBuilderDelegate((context, index) => ListTile(title: Text('条目 \\$index')), childCount: 20),
    ),
  ],
)

PageView

说明:PageView 用于页面翻页(轮播或分页视图)。

属性:

  • key – Widget 的 key(Key)。
  • scrollDirection – 滚动方向(Axis)。
  • controller – 页控制器(PageController)。
  • physics – 滚动物理(ScrollPhysics)。
  • pageSnapping – 是否自动对齐到页面(bool)。
  • onPageChanged – 页面变化回调(ValueChanged<int>)。
  • children – 页面列表(List<Widget>)。
  • allowImplicitScrolling – 是否允许隐式滚动(bool)。

示例:

PageView(
  children: [
    Container(color: Colors.red),
    Container(color: Colors.green),
    Container(color: Colors.blue),
  ],
)
暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇