【开源鸿蒙跨平台开发--Flutter】Flutter 全组件深度解析手册

Flutter全组件深度解析

《Flutter 全组件深度解析手册》

文档说明: 本文档旨在全面解析 Flutter 框架中的 UI 组件(Widgets),涵盖从基础到高阶的各个方面。每个组件包含定义、应用场景、核心属性详解及完整代码示例。


目录大纲 (Blueprint)

  1. 第一章:基础核心组件 (Basic Widgets)
    • Text (文本) & RichText
    • Image (图片) & Icon
    • Buttons (按钮家族:Elevated, Text, Outlined)
    • Scaffold (脚手架) & AppBar
  2. 第二章:布局组件 (Layout Widgets)
    • 单子元素布局:Container, Center, Padding, Align, SizedBox
    • 多子元素布局:Row, Column, Flex, Stack, Positioned, Wrap
  3. 第三章:容器与装饰 (Styling & Assets)
    • DecoratedBox & BoxDecoration
    • Opacity, ClipRRect (裁剪), Transform
    • Card (卡片)
  4. 第四章:滚动与列表 (Scrolling Widgets)
    • ListView (列表)
    • GridView (网格)
    • SingleChildScrollView
    • CustomScrollView & Slivers (高级滚动)
  5. 第五章:表单与输入 (Input & Forms)
    • TextField (文本输入框)
    • Form & TextFormField
    • Checkbox, Radio, Switch, Slider
  6. 第六章:弹窗与提示 (Dialogs & Alerts)
    • AlertDialog, SimpleDialog
    • BottomSheet
    • SnackBar
  7. 第七章:导航与路由 (Navigation)
    • Navigator
    • BottomNavigationBar, TabBar
    • Drawer (侧边栏)
  8. 第八章:功能性组件 (Functional Widgets)
    • GestureDetector & InkWell (手势)
    • Theme (主题)
    • FutureBuilder & StreamBuilder (异步UI)

第一部分:核心基础组件与布局详解

1. Text (文本组件)

说明:
Text 是 Flutter 中最基础的组件,用于在屏幕上显示单一样式的文本字符串。

核心属性 (Properties):

属性名类型说明
dataString要显示的字符串内容(必填,位置参数)。
styleTextStyle文本样式(颜色、字体、大小、粗细等)。
textAlignTextAlign文本对齐方式 (center, left, right, justify)。
maxLinesint文本显示的最大行数。
overflowTextOverflow超出最大行数时的处理方式 (ellipsis, fade, clip)。
softWrapbool是否自动换行。

TextStyle 常用属性:

  • color: 字体颜色。
  • fontSize: 字体大小 (double)。
  • fontWeight: 字体粗细 (FontWeight.bold, FontWeight.w400)。
  • fontStyle: 字体样式 (FontStyle.italic)。
  • decoration: 装饰线 (TextDecoration.underline, lineThrough)。

代码示例:

import 'package:flutter/material.dart';

class TextExample extends StatelessWidget {
  
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        // 1. 基础文本
        const Text("Hello Flutter"),

        // 2. 带样式的文本
        Text(
          "Styled Text",
          style: TextStyle(
            color: Colors.blue,
            fontSize: 24.0,
            fontWeight: FontWeight.bold,
            letterSpacing: 2.0, // 字符间距
          ),
        ),

        // 3. 长文本截断
        Container(
          width: 200,
          color: Colors.grey[200],
          child: Text(
            "这是一段非常非常长的文本,用来测试 Text 组件的 overflow 属性,当文字超出容器宽度时会显示省略号。",
            maxLines: 1,
            overflow: TextOverflow.ellipsis, // 显示省略号 ...
            style: TextStyle(fontSize: 16),
          ),
        ),
      ],
    );
  }
}

2. Image (图片组件)

说明:
Image 组件用于显示多种格式的图片。Flutter 提供了多种构造函数来加载不同来源的图片。

常用构造函数:

  1. Image.asset: 加载项目资源目录中的图片。
  2. Image.network: 加载网络图片。
  3. Image.file: 加载本地文件系统中的图片。
  4. Image.memory: 加载 Uint8List 内存图片。

核心属性 (Properties):

属性名类型说明
width / heightdouble图片的宽和高。
fitBoxFit图片的填充模式 (cover, contain, fill, fitWidth 等)。
alignmentAlignment图片在容器内的对齐方式。
repeatImageRepeat图片未填满容器时的重复方式。

BoxFit 详解:

  • BoxFit.cover: 等比缩放,填满容器,可能会裁剪部分图片。
  • BoxFit.contain: 等比缩放,完整显示图片,可能会留白。
  • BoxFit.fill: 拉伸填满,图片会变形。

代码示例:

import 'package:flutter/material.dart';

class ImageExample extends StatelessWidget {
  
  Widget build(BuildContext context) {
    return Column(
      children: [
        // 1. 网络图片
        Image.network(
          'https://flutter.github.io/assets-for-api-docs/assets/widgets/owl.jpg',
          width: 100,
          height: 100,
          fit: BoxFit.cover,
        ),
        
        SizedBox(height: 20),

        // 2. 本地资源图片 (需在 pubspec.yaml 中配置 assets)
        // Image.asset('assets/images/logo.png'),
        
        // 3. 圆形图片 (配合 ClipOval)
        ClipOval(
          child: Image.network(
            'https://flutter.github.io/assets-for-api-docs/assets/widgets/owl.jpg',
            width: 80,
            height: 80,
            fit: BoxFit.cover,
          ),
        )
      ],
    );
  }
}

3. Container (万能容器)

说明:
Container 是 Flutter 中最常用的组合型组件。它本身结合了 Padding (内边距)、Align (对齐)、ConstrainedBox (尺寸限制) 和 DecoratedBox (装饰) 等功能。

核心属性 (Properties):

属性名类型说明
alignmentAlignment子组件在容器内的对齐方式。
paddingEdgeInsets内边距。
marginEdgeInsets外边距。
colorColor背景色(若使用了 decoration,则必须在 decoration 中设置颜色)。
decorationDecoration背景装饰(圆角、边框、阴影、渐变)。
width / heightdouble强制宽高。
childWidget子组件。
constraintsBoxConstraints尺寸约束。

代码示例:

import 'package:flutter/material.dart';

class ContainerExample extends StatelessWidget {
  
  Widget build(BuildContext context) {
    return Center(
      child: Container(
        // 尺寸
        width: 300,
        height: 200,
        
        // 对齐方式
        alignment: Alignment.center,
        
        // 边距
        margin: EdgeInsets.all(20), // 外边距
        padding: EdgeInsets.symmetric(horizontal: 20, vertical: 10), // 内边距
        
        // 装饰 (核心)
        decoration: BoxDecoration(
          color: Colors.blueAccent, // 背景色
          borderRadius: BorderRadius.circular(15), // 圆角
          border: Border.all(color: Colors.white, width: 2), // 边框
          boxShadow: [ // 阴影
            BoxShadow(
              color: Colors.black26,
              offset: Offset(4, 4),
              blurRadius: 10,
            )
          ],
          gradient: LinearGradient( // 渐变
            colors: [Colors.blue, Colors.lightBlueAccent],
            begin: Alignment.topLeft,
            end: Alignment.bottomRight,
          ),
        ),
        
        // 子元素
        child: Text(
          "Super Container",
          style: TextStyle(color: Colors.white, fontSize: 20),
        ),
      ),
    );
  }
}

4. Row & Column (线性布局)

说明:

  • Row: 水平方向排列子组件。
  • Column: 垂直方向排列子组件。
    它们都继承自 Flex 组件,不仅是布局的基础,也是最易出错的地方(如溢出错误)。

核心属性 (Properties):

属性名类型说明
childrenList<Widget>子组件列表。
mainAxisAlignmentMainAxisAlignment主轴对齐方式。
crossAxisAlignmentCrossAxisAlignment交叉轴对齐方式。
mainAxisSizeMainAxisSize主轴尺寸 (max: 占满剩余空间, min: 仅包裹子组件)。

轴的概念 (Axis):

  • 对于 Row:主轴是水平方向 (Left -> Right),交叉轴是垂直方向。
  • 对于 Column:主轴是垂直方向 (Top -> Bottom),交叉轴是水平方向。

MainAxisAlignment 选项:

  • start: 靠起点。
  • end: 靠终点。
  • center: 居中。
  • spaceBetween: 两端对齐,中间留白。
  • spaceAround: 每个元素两侧留白相等。
  • spaceEvenly: 元素之间和两端的间距均等。

代码示例:

import 'package:flutter/material.dart';

class LayoutExample extends StatelessWidget {
  
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("Row & Column")),
      body: Column(
        // Column 的主轴是垂直方向
        mainAxisAlignment: MainAxisAlignment.spaceEvenly, 
        // Column 的交叉轴是水平方向
        crossAxisAlignment: CrossAxisAlignment.center, 
        children: [
          Container(color: Colors.red, width: 50, height: 50),
          
          // 嵌套 Row
          Row(
            // Row 的主轴是水平方向
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Icon(Icons.star, color: Colors.yellow),
              Text("Favorites"),
              Icon(Icons.star, color: Colors.yellow),
            ],
          ),
          
          Container(color: Colors.blue, width: 50, height: 50),
        ],
      ),
    );
  }
}

5. Stack & Positioned (层叠布局)

说明:
Stack 允许子组件堆叠在一起(类似 Photoshop 的图层)。默认情况下,后添加的组件会覆盖在先添加的组件之上。Positioned 组件只能在 Stack 中使用,用于精确定位子组件。

核心属性 (Stack):

  • alignment: 未定位子组件的默认对齐方式。
  • fit: 未定位子组件如何适应 Stack 的大小 (StackFit.loose / expand)。

核心属性 (Positioned):

  • top, bottom, left, right: 距离 Stack 边缘的距离 (double)。
  • width, height: 强制尺寸。

代码示例:

import 'package:flutter/material.dart';

class StackExample extends StatelessWidget {
  
  Widget build(BuildContext context) {
    return Center(
      child: Container(
        width: 300,
        height: 300,
        color: Colors.grey[300],
        child: Stack(
          alignment: Alignment.center, // 默认居中
          children: [
            // 底层
            Container(width: 200, height: 200, color: Colors.red),
            
            // 中间层
            Container(width: 150, height: 150, color: Colors.green),
            
            // 顶层 - 绝对定位
            Positioned(
              right: 10,
              bottom: 10,
              child: Container(
                width: 50,
                height: 50,
                color: Colors.blue,
                child: Center(child: Text("Top")),
              ),
            ),
            
            // 顶层 - 另一种定位
            Positioned(
              top: 20,
              left: 20,
              child: Icon(Icons.favorite, color: Colors.white, size: 40),
            )
          ],
        ),
      ),
    );
  }
}

6. Buttons (按钮组件家族)

说明:
Flutter 2.0 之后引入了新的按钮风格,主要包括 ElevatedButton (原 RaisedButton), TextButton (原 FlatButton), 和 OutlinedButton (原 OutlineButton)。

通用属性:

  • onPressed: 点击回调函数。如果为 null,按钮会被禁用。
  • child: 按钮显示的内容(通常是 Text 或 Icon)。
  • style: ButtonStyle,用于深度定制按钮外观。

代码示例:

import 'package:flutter/material.dart';

class ButtonExample extends StatelessWidget {
  
  Widget build(BuildContext context) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        // 1. 漂浮按钮 (有背景色和阴影)
        ElevatedButton(
          onPressed: () {
            print("Elevated Button Pressed");
          },
          style: ElevatedButton.styleFrom(
            backgroundColor: Colors.blue, // 背景色
            foregroundColor: Colors.white, // 文字/图标色
            elevation: 5, // 阴影高度
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(20), // 圆角
            ),
          ),
          child: Text("提交"),
        ),
        
        SizedBox(height: 20),

        // 2. 文本按钮 (无背景,点击有水波纹)
        TextButton(
          onPressed: () {},
          child: Text("取消"),
        ),

        SizedBox(height: 20),

        // 3. 边框按钮
        OutlinedButton(
          onPressed: () {},
          style: OutlinedButton.styleFrom(
            side: BorderSide(color: Colors.red, width: 2),
          ),
          child: Text("删除"),
        ),
        
        SizedBox(height: 20),
        
        // 4. 带图标的按钮 (使用 .icon 构造函数)
        ElevatedButton.icon(
          onPressed: () {},
          icon: Icon(Icons.send),
          label: Text("发送"),
        )
      ],
    );
  }
}

7. Scaffold (脚手架)

说明:
Scaffold 实现了基本的 Material Design 视觉布局结构。它提供了 App 的主要框架,如顶部导航栏、侧边栏、底部导航栏、悬浮按钮等。

核心属性 (Properties):

属性名类型说明
appBarPreferredSizeWidget顶部应用栏 (通常是 AppBar)。
bodyWidget内容主体区域。
floatingActionButtonWidget悬浮操作按钮。
drawerWidget左侧抽屉菜单。
endDrawerWidget右侧抽屉菜单。
bottomNavigationBarWidget底部导航栏。
backgroundColorColor页面背景色。

代码示例:

import 'package:flutter/material.dart';

class ScaffoldExample extends StatefulWidget {
  
  _ScaffoldExampleState createState() => _ScaffoldExampleState();
}

class _ScaffoldExampleState extends State<ScaffoldExample> {
  int _selectedIndex = 0;

  
  Widget build(BuildContext context) {
    return Scaffold(
      // 1. 顶部导航栏
      appBar: AppBar(
        title: Text("首页"),
        centerTitle: true,
        actions: [
          IconButton(icon: Icon(Icons.search), onPressed: () {}),
        ],
      ),

      // 2. 左侧侧边栏
      drawer: Drawer(
        child: ListView(
          padding: EdgeInsets.zero,
          children: [
            DrawerHeader(
              decoration: BoxDecoration(color: Colors.blue),
              child: Text("Menu", style: TextStyle(color: Colors.white, fontSize: 24)),
            ),
            ListTile(title: Text("设置"), leading: Icon(Icons.settings)),
            ListTile(title: Text("关于"), leading: Icon(Icons.info)),
          ],
        ),
      ),

      // 3. 内容区域
      body: Center(
        child: Text("当前选中页面索引: $_selectedIndex", style: TextStyle(fontSize: 20)),
      ),

      // 4. 悬浮按钮
      floatingActionButton: FloatingActionButton(
        onPressed: () {},
        child: Icon(Icons.add),
        tooltip: 'Add',
      ),

      // 5. 底部导航栏
      bottomNavigationBar: BottomNavigationBar(
        currentIndex: _selectedIndex,
        onTap: (index) {
          setState(() {
            _selectedIndex = index;
          });
        },
        items: [
          BottomNavigationBarItem(icon: Icon(Icons.home), label: "首页"),
          BottomNavigationBarItem(icon: Icon(Icons.business), label: "业务"),
          BottomNavigationBarItem(icon: Icon(Icons.person), label: "我的"),
        ],
      ),
    );
  }
}

第一部分总结:
上述内容涵盖了构建一个 Flutter 页面最基础的“积木”。TextImage 用于展示内容,ContainerRowColumnStack 用于排版布局,而 Scaffold 则是组合这些元素的页面骨架。


评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值