0603-Flutter

第一章 Flutter概述

第二章 Flutter基础

2.1 Flutter项目结构

  • 使用AndroidStudio或者VSCode开发工具创建Flutter项目:目录结构说明

    文件或目录 说明
    .dart_tool 记录了一些dart工具库所在的位置和信息
    .idea android studio 是基于idea开发的,.idea 记录了项目的一些文件的变更记录
    android Android项目文件夹
    ios iOS项目文件夹
    lib lib文件夹内存放我们的dart语音代码
    test 用于存放我们的测试代码
    .gitignore git忽略配置文件
    .metadata IDE 用来记录某个 Flutter 项目属性的的隐藏文件
    .packages pub 工具需要使用的,包含 package 依赖的 yaml 格式的文件
    flutter_app.iml 工程文件的本地路径配置
    pubspec.lock 当前项目依赖所生成的文件
    pubspec.yaml 当前项目的一些配置文件,包括依赖的第三方库、图片资源文件等
    README.md READEME文件

2.2 Flutter UI风格

  1. Material:Material Design是由谷歌推出的全新设计语言,这种设计语言旨在为手机、平板电脑、台式机和其他平台提供更一致、更广泛的外观和感觉。Material Design风格是一直非常有质感的设计风格,并会提供一些默认的交互动画,对于搞Android开发的来说应该耳熟能详了。MaterialApp代表使用Material Design风格的应用,里面包含了其他所需的基本控件。

    1
    import 'package:flutter/material.dart';
  2. Cupertino:Cupertino风格组件即IOS风格组件。主要有CupertinoTabBar、CupertinoPageScaffold、CupertinoTabScaffold、CupertinoTabView等。目前组件库还没有Material Design风格组件丰富。

    1
    import 'package:flutter/cupertino.dart';

2.3 Widget概述

        Flutter Widget采用现代响应式框架构建,这是从React中获得的灵感,中心思想是用widget构建你的UI。 Widget描述了他们的视图在给定其当前配置和状态时应该看起来像什么。当widget的状态发生变化时,widget会重新构建UI,Flutter会对比前后变化的不同, 以确定底层渲染树从一个状态转换到下一个状态所需的最小更改。

        在Flutter中几乎所有的对象都是一个 widget,它不仅可以表示UI元素,也可以表示一些功能性的组件。在 Flutter中widget 的功能是“描述一个UI元素的配置信息(是 Widget 接收的参数)”,它就是说, Widget 其实并不是表示最终绘制在设备屏幕上的显示元素,而是根据配置信息最终生成Layer树然后显示。Flutter中根据Widget的布局绘制流程如下:

  1. 根据 Widget 树生成一个 Element 树,Element 树中的节点都继承自 Element 类。
  2. 根据 Element 树生成 Render 树(渲染树),渲染树中的节点都继承自RenderObject 类。
  3. 根据渲染树生成 Layer 树,然后上屏显示,Layer 树中的节点都继承自 Layer 类。

这里需要注意:

  1. 三棵树中,Widget 和 Element 是一一对应的,但并不和 RenderObject 一一对应。比如 StatelessWidgetStatefulWidget 都没有对应的 RenderObject。
  2. 渲染树在上屏前会生成一棵 Layer 树

2.4 MaterialApp结构

        一个最简单的Flutter应用程序,只需一个widget即可!如下面示例:将一个widget传给runApp函数即可。使用Material的UI风格,可以继承主题数,widget需要位于MaterialApp内才能正常显示, 因此我们使用MaterialApp来运行该应用。Material也是widget组件树组成一套UI风格,就好像html也是由不同html标签组成的DOM树,所以学习Flutter主要是学习Material中的组件使用方式;MaterialApp中的组件基本结构如下图:

  • Scallold是Material中提供的基础的页面脚手架,包含Flutter应用主要展示的页面;

2.5 组件状态

  1. 状态概述:项目开发中,通常根据是否需要进行数据交互分为有状态组件(StatefulWidget)和无状态组件(StatelessWidget)。widget的主要工作是实现一个build函数,用以构建自身。

  2. 无状态组件:StatelessWidget

    1
    2
    3
    4
    5
    6
    7
    8
    class 组件类名 extends StatelessWidget {
    const 组件类名({Key? key}) : super(key: key);

    @override
    Widget build(BuildContext context) {
    return Container();
    }
    }
  3. 有状态组件:StatefulWidget:可以在_State对象中定义需要交互的数据信息

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    class 组件类名 extends StatefulWidget {
    const 组件类名({Key? key}) : super(key: key);

    @override
    _State createState() => _State();
    }

    class _State extends State<> {
    @override
    Widget build(BuildContext context) {
    return Container();
    }
    }

2.6 包管理

  1. pubspec.yaml:在软件开发中,将代码单独抽到一个独立模块,项目需要使用时再直接集成这个模块,便可大大提高开发效率。一个 App 在实际开发中往往会依赖很多包,手动来管理应用中的依赖包将会非常麻烦。 Flutter 使用配置文件pubspec.yaml(位于项目根目录)来管理第三方依赖包。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    name: flutter_in_action
    description: First Flutter Application.

    version: 1.0.0+1

    dependencies:
    flutter:
    sdk: flutter
    cupertino_icons: ^0.1.2

    dev_dependencies:
    flutter_test:
    sdk: flutter

    flutter:
    uses-material-design: true
    • name:应用或包名称。
    • description: 应用或包的描述、简介。
    • version:应用或包的版本号。
    • dependencies:应用或包依赖的其它包或插件。
    • dev_dependencies:开发环境依赖的工具包(而不是flutter应用本身依赖的包)。
    • flutter:flutter相关的配置选项。
  2. Pub仓库:Pub(https://pub.dev/ )是 Google 官方的 Dart Packages 仓库,类似于 node 中的 npm仓库。我们可以在 Pub 上面查找我们需要的包和插件,也可以向 Pub 发布我们的包和插件。使用方式

    • 搜索支持Flutter的包以及对应的版本

    • 将包添加到Flutter项目的配置文件中

      1
      2
      3
      4
      5
      dependencies:
      flutter:
      sdk: flutter
      # 新添加的依赖
      english_words: ^4.0.0
    • 执行pub get命令将第三方包拉取到当前项目中

    • 在dart项目中import对应的包(dart基础:每个dart文件就属于一个包,引入后可以使用非私有对象)

  3. 其它依赖方式

    • 依赖本地包

      1
      2
      3
      dependencies:
      pkg1:
      path: ../../code/pkg1
    • 依赖Git -> 软件包位于仓库的根目录中

      1
      2
      3
      4
      dependencies:
      pkg1:
      git:
      url: git://github.com/xxx/pkg1.git
    • 依赖Git -> 软件包不在仓库的根目录中可以使用path参数指定相对位置

      1
      2
      3
      4
      5
      dependencies:
      package1:
      git:
      url: git://github.com/flutter/packages.git
      path: packages/package1

2.7 状态管理

2.8 路由管理

2.9 Flutter API

  1. Json与Map

    1
    2
    3
    4
    5
    6
    import 'dart:convert';
    // Map 转 JSON字符串
    json.encode(mapObj);

    // Json 解码,结果为Map
    json.decode(jsonString);
  2. 网络请求第三方库:http

    • Flutter下载http库

      1
      2
      3
      4
      5
        ```

      - 引入http组件

      ```dart
    • 发送请求案例

      1
      2
      3
      4
      5
      6
      7
      8
           ```

      3. 网络请求第三方库:dio

      - Flutter下载dio库

      ```sh

    • 引入dio库

      1
           
    • 发送请求

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      24
      25
      26
      27
      28
      29
      30
      31
      32
      33
      34
      35
      36
      37
      38
      39
      40
      41
      42
      43
      44
      45
      46
      47
      48
      49
      50
      51
      52
      53
      54
      55
      56
      57
      58
      59
      60
      61
      62
      63
      64
      65
      66
      67
      68
      69
      70
      71
      72
      73
      74
      75
      76
      77
      78
      79
           ```



      # 第三章 Material基础

      ## 3.1 Scaffold

      - Scaffold属性

      | Scaffold属性 | 类型 | 介绍 |
      | ------------------------------ | ---------------------------- | ------------------------------------------------------------ |
      | appBar | PreferredSizeWidget | 页面上方导航条 |
      | body | Widget | 页面容器 |
      | floatingActionButton | Widget | 悬浮按钮 |
      | floatingActionButtonLocation | FloatingActionButtonLocation | 悬浮按钮位置 |
      | floatingActionButtonAnimator | FloatingActionButtonAnimator | 悬浮按钮动画 |
      | persistentFooterButtons | `List<Widget>` | 显示在底部导航条上方的一组按钮 |
      | drawer | Widget | 左侧菜单 |
      | onDrawerChanged | DrawerCallback | |
      | endDrawer | Widget | 右侧菜单 |
      | onEndDrawerChanged | DrawerCallback | |
      | bottomNavigationBar | Widget | 底部导航条 |
      | bottomSheet | Widget | 一个持久停留在body下方,底部控件上方的控件 |
      | backgroundColor | Color | 背景色 |
      | resizeToAvoidBottomPadding | bool | 已废弃,resizeToAvoidBottomInset作为替代 |
      | resizeToAvoidBottomInset | bool | 默认为 true,防止一些小组件重复 |
      | primary | bool | 是否在屏幕顶部显示Appbar, 默认为 true,Appbar 是否向上延伸到状态栏,如电池电量,时间那一栏 |
      | drawerDragStartBehavior | DragStartBehavior | 控制 drawer 的一些特性 |
      | extendBody | bool | body 是否延伸到底部控件 |
      | extendBodyBehindAppBar | bool | 默认 false,为 true 时,body 会置顶到 appbar 后,如appbar 为半透明色,可以有毛玻璃效果 |
      | drawerScrimColor | Color | 侧滑栏拉出来时,用来遮盖主页面的颜色 |
      | drawerEdgeDragWidth | double | 侧滑栏拉出来的宽度 |
      | drawerEnableOpenDragGesture | bool | 左侧侧滑栏是否可以滑动 |
      | endDrawerEnableOpenDragGesture | bool | 右侧侧滑栏是否可以滑动 |

      ## 3.2 AppBar

      - AppBar属性

      | AppBar属性 | 介绍 |
      | ------------------------- | ------------------------------------------------------------ |
      | leading | 可以定制左上角按钮 |
      | automaticallyImplyLeading | 是否自动导入左上角按钮,默认为 true,例如默认导入返回按钮 |
      | title | AppBar 标题 |
      | actions | 右上角功能按钮,可自定义 |
      | flexibleSpace | 可折叠的应用栏,在改变 appBar 的 size 时有效果 |
      | bottom | AppBar下方悬浮栏 |
      | elevation | 阴影高度,默认为4.0 |
      | shadowColor | 阴影颜色 |
      | shape | 阴影 ShapeBorder |
      | backgroundColor | AppBar 背景色 |
      | brightness | Brightness.dark 和 Brightness.light,改变上方电池,时间等状态栏颜色 |
      | iconTheme | 所有 icon 的主题 |
      | actionsIconTheme | actions 里的所有 icon 主题 |
      | textTheme | text 主题 |
      | primary | AppBar 是否在整个屏幕最上方,为 true 时,距离 AppBar 贴合状态栏下方,false 时,贴合整个屏幕最上方 |
      | centerTitle | title 是否居中 |
      | excludeHeaderSemantics | 标题是否应该用头 [Semantics]. 默认为false,没太大用 |
      | titleSpacing | title 距离左侧偏移量 |
      | toolbarOpacity | AppBar 透明度 |
      | bottomOpacity | bottom 透明度 |
      | toolbarHeight | AppBar 高度 |

      ## 3.3 Drawer&EndDrawer

      - Drawer(抽屉组件):可以实现类似抽屉拉出和推入的效果,可以从侧边栏拉出导航面板。通常Drawer是和ListView组件组合使用的。Drawer是个抽屉组件,组件内容由其他Widget实现,可以添加头部效果,用DrawerHeader和UserAccountsDrawerHeader这两个组件可以实现。添加Drawer组件,Scaffold会自动给我们生成一个Drawer的按钮,如果我们在appBar中手动设置leading,确实是会更改这个按钮的图标,但是点击这个图标就不会弹出Drawer了,所以如果我们有需要自定义Drawer的图标的话

      ```dart
      leading: Builder(
      builder: (BuildContext context){
      return IconButton(
      icon: Icon(Icons.wifi_tethering),
      onPressed: (){
      Scaffold.of(context).openDrawer();
      }
      );
      }
      ),
  • DrawerHeader:展示基本信息

    属性名 类型 说明
    decoration Decoration header区域的decoration,通常用来设置背景颜色或者背景图片
    curve Curve 如果decoration发生了变化,则会使用curve设置的变化曲线和duration设置的动画时间来做一个切换动画
    child Widget header里面所显示的内容控件
    padding EdgeInsetsGeometry header里面内容控件的padding指。如果child为null的话,则这个值无效
    margin EdgeInsetsGeometry header四周的间隙
  • UserAccountsDraweHeader:展示用户头像、用户名、Email等信息

    属性名 类型 说明
    margin EdgeInsetsGeometry Header四周的间隙
    decoration Decoration header区域的decoration,通常用来设置背景颜色或者背景图片
    currentAccountPicture Widget 用来设置当前用户的头像
    otherAccountsPictures List 用来设置当前用户其他账号的头像
    accountName Widget 当前用户名
    accountEmail Widget 当前用户Email
    onDetailsPressed VoidCallBack 当accountName或accountEmail被点击的时候所触发的回调函数,可以用来显示其他额外的信息

3.4 FloatingActionButton

  • FloatingActionButton 是一个悬浮在内容上的圆形图标按钮,每个屏幕中最多使用一个浮动按钮。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    const FloatingActionButton({
    Key key,
    this.child,// 子组件 一般为Icon
    this.tooltip,// 文字解释,长按时显示
    this.foregroundColor,// 前景色
    this.backgroundColor, // 背景色
    this.heroTag = const _DefaultHeroTag(), // hero效果使用的tag,系统默认会给所有FAB使用同一个tag,方便做动画效果
    this.elevation = 6.0, // 未点击时的阴影值
    this.highlightElevation = 12.0, // 点击时的阴影值
    @required this.onPressed, // 点击事件回调
    this.mini = false, // 是否是 mini类型
    this.shape = const CircleBorder(), // 设置shape时,默认的elevation将会失效,默认为CircleBorder
    this.clipBehavior = Clip.none, //
    this.materialTapTargetSize,
    this.isExtended = false, // 是否为”extended”类型
    })

3.5 BottomNavigationBar

  • bottomNavigationBar 是属于 Scaffold 中的一个位于底部的控件。通常和 BottomNavigationBarItem 配合使用

    属性 类型 说明
    items List 底部导航栏的显示项
    onTap 点击导航栏子项时的回调
    currentIndex int 当前显示项的下标
    type BottomNavigationBarType 底部导航栏的类型,有fixed和shifting两个类型
    fixedColor Color 底部导航栏type为fixed时导航栏的颜色
    iconSize double BottomNavigationBarItem icon的大小
  • BottomNavigationBarItem

    属性 类型 说明
    icon Widget 要显示的图标控件,一般都是Iocn
    title Widget 要显示的标题控件,一般都是Text
    activeIcon Widget 选中时要显示的icon,一般也是Icon
    backgroundColor Color BottomNavigationBarType为shifting时的背景颜色

第四章 基础组件

4.1 基础组件

1. 颜色:Color

  • 颜色常用格式

    1
    2
    3
    4
    Color c1 = Color(0xFF3CAAFA);
    Color c2 = Color.fromRGBO(60, 170, 250, 1);
    Color c3 = Color.fromARGB(255, 60, 170, 250);
    Color c5 = Colors.blue;
    1. Color(int value):value接收的是一个十六进制(0x开头),前两位表示的是十六进制透明度(00-FF),后六位是十六进制色值。
    2. Color.fromRGBO(int r, int g, int b, double opacity):r、g、b分别表示red、green、blue,常规的红绿蓝三色,取值范围为0-255,opacity表示透明度,取值0.0-1.0。
    3. Color.fromARGB(int a, int r, int g, int b):a表示透明度,取值0-255,rgb同上一样。
    4. Colors._():Colors类定义了很多颜色,可以直接使用
  • 自定义颜色:举例如下,根据业务需求定义静态颜色对象

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    import 'package:color_dart/RgbaColor.dart';
    import 'package:flutter/material.dart';

    class ThemeColors {
    ///主色调,按钮,特殊需要强调和突出的文字 -- 支付宝蓝色
    static Color colorTheme = Color.fromRGBO(56, 117, 246, 1);
    ///static Color colorTheme = rgba(56, 117, 246, 1);
    ///主色调渐变用色,个别按钮和状态,从colorBtnLeft变化到colorBtnRight
    static Color colorBtnLeft = Color.fromRGBO(255, 251, 156, 51);
    static Color colorBtnRight = Color.fromRGBO(255, 252, 191, 50);
    ///提示性文字,状态信息,按钮等
    static Color colorRed = Color.fromRGBO(255, 226, 36, 39);
    ///功能性较强的文字,内页标题等
    static Color color333333 = Color.fromRGBO(255, 51, 51, 51);
    ///正文,副标题以及可点击区域的主要文字和图标
    static Color color666666 = Color.fromRGBO(255, 102, 102, 102);
    ///弱化信息,提示性文字信息,不可点击状态
    static Color color999999 = Color.fromRGBO(255, 153, 153, 153);
    ///弱化信息,提示性文字信息
    static Color colorDDDDDD = Color.fromARGB(255, 221, 221, 221);
    ///背景区域划分,分割线
    static Color colorF6F6F8 = Color.fromARGB(255, 246, 246, 248);
    ///纯白色
    static Color colorWhite = Color.fromARGB(255, 255, 255, 255);
    ///纯黑色
    static Color colorBlack = Color.fromARGB(255, 0, 0, 0);
    }
  • 封装十六进制颜色工具类:使用十六进制颜色的时候透明度使用的比较少,封装十六进制方法默认透明为1;

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    class ColorsUtil {
    /// 十六进制颜色,
    /// hex, 十六进制值,例如:0xffffff,
    /// alpha, 透明度 [0.0,1.0]
    static Color hexColor(int hex,{double alpha = 1}){
    if (alpha < 0){
    alpha = 0;
    }else if (alpha > 1){
    alpha = 1;
    }
    return Color.fromRGBO((hex & 0xFF0000) >> 16 ,
    (hex & 0x00FF00) >> 8,
    (hex & 0x0000FF) >> 0,
    alpha);
    }
    }

2. 图标:Icon

  • Material内置图标:Google图标库

    1
    Icon(Icons.图标名称),
  • 使用自定义图标

    1. 阿里巴巴图标库下载字体图标:https://www.iconfont.cn/,并解压添加ttf文件到Flutter项目中

    2. 在pubspec.yaml文件中配置字体

      1
      2
      3
      4
      fonts:
      - family: myIcons
      fonts:
      - asset: assets/fonts/iconfont.ttf
    3. 定义自定义图标的名称:自定义一个Icon工具类,添加的图标定义名称.

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      24
      25
      26
      27
      28
      29
      30
      import 'package:flutter/material.dart';
      // 下面代码中的 blog home book 是自己定义的图标名称,
      //不做规范适情况而改。
      class MyIcons{
      static const IconData blog= const IconData(
      0xe722,
      fontFamily: "myIcons",
      matchTextDirection: true
      );
      static const IconData home= const IconData(
      0xe619,
      fontFamily: "myIcons",
      matchTextDirection: true
      );
      static const IconData book= const IconData(
      0xe623,
      fontFamily: "myIcons",
      matchTextDirection: true
      );
      static const IconData video= const IconData(
      0xe614,
      fontFamily: "myIcons",
      matchTextDirection: true
      );
      static const IconData mine= const IconData(
      0xe600,
      fontFamily: "myIcons",
      matchTextDirection: true
      );
      }

      第一个参数是codePoint值,在图标压缩包中的demo_index.html文件中可以查看,把&#改成0就好

    4. 使用自定义图标

      1
      icon: Icon(MyIcons.home)

3. 文字:Text

  • Text参数说明

    参数 类型 说明
    data String 必传:要显示的字符串
    style TextStyle 文本样式
    strutStyle StrutStyle
    textAlign TextAlign 水平对齐方式
    - TextAlign.center:将文本对齐容器的中心。
    - TextAlign.end:对齐容器后缘上的文本。
    - TextAlign.justify:拉伸以结束的文本行以填充容器的宽度
    - TextAlign.left:对齐容器左边缘的文本。
    - TextAlign.right:对齐容器右边缘的文本。
    - TextAlign.start:对齐容器前缘上的文本。
    textDirection TextDirection 文本方向
    - TextDirection.ltr:文本从左向右流动
    - TextDirection.rtl:文本从右向左流动
    locale Locale 用于选择区域特定字形的语言环境
    softWrap bool 文本过长,是否需要换行
    overflow TextOverflow 处理视觉溢出
    - TextOverflow.clip:剪切溢出的文本
    - TextOverflow.ellipsis:使用省略号表示
    - TextOverflow.fade:将溢出的文本淡化为透明
    textScaleFactor double 每个逻辑像素的字体像素数
    maxLines int 文本要跨越的可选最大行数,为1,则文本不会换行
    semanticsLabel String 图像的语义描述,用于向Andoid上的TalkBack和iOS上的VoiceOver提供图像描述
    textWidthBasis TextWidthBasis
    textHeightBehavior TextHeightBehavior
  • TextStyle文本样式

    参数 类型 说明
    color Color 文本颜色。如果指定了foreground,则此值必须为null。
    decoration TextDecoration 绘制文本装饰
    - 下划线(TextDecoration.underline)
    - 上划线(TextDecoration.overline)
    - 删除线(TextDecoration.lineThrough)
    - 无(TextDecoration.none)
    decorationColor Color 绘制文本装饰的颜色。
    decorationStyle TextDecorationStyle 绘制文本装饰的样式:
    - 画一条虚线 TextDecorationStyle.dashed
    - 画一条虚线 TextDecorationStyle.dotted
    - 画两条线 TextDecorationStyle.double
    - 画一条实线 TextDecorationStyle.solid
    - 画一条正弦线(波浪线) TextDecorationStyle.wavy
    fontWeight FontWeight 绘制文本时使用的字体粗细
    - FontWeight.bold 常用的字体重量比正常重。即w700
    - FontWeight.normal 默认字体粗细。即w400
    - FontWeight.w100 薄,最薄
    - FontWeight.w200 特轻
    - FontWeight.w300 轻
    - FontWeight.w400 正常/普通/平原
    - FontWeight.w500 较粗
    - FontWeight.w600 半粗体
    - FontWeight.w700 加粗
    - FontWeight.w800 特粗
    - FontWeight.w900 最粗
    fontStyle FontStyle 字体变体:
    - FontStyle.italic 使用斜体
    - FontStyle.normal 使用直立
    textBaseline TextBaseline 对齐文本的水平线:
    - TextBaseline.alphabetic:文本基线是标准的字母基线
    - TextBaseline.ideographic:文字基线是表意字基线;如果字符本身超出了alphabetic 基线,那么ideograhpic基线位置在字符本身的底部。
    fontFamily String 使用的字体名称
    fontSize double 字体大小(pt、sp),默认为14个逻辑像素(14pt、14sp)
    letterSpacing double 水平字母之间的空间间隔
    wordSpacing double 单词之间添加的空间间隔
    height double 文本行与行的高度,作为字体大小的倍数(取值1~2,如1.2)
    background Paint 文本背景色
    foreground Paint 文本的前景色
    shadows List<Shadow> 背景设定(边框、圆角、阴影、形状、渐变、背景图像等)
    - BoxDecoration:实现边框、圆角、阴影、形状、渐变、背景图像
    - ShapeDecoration:实现四个边分别指定颜色和宽度、底部线、矩形边色、圆形边色、体育场(竖向椭圆)、 角形(八边角)边色
    - FlutterLogoDecoration:实现Flutter图片
    - UnderlineTabindicator:下划线

4. 富文本:RichText

  • 富文本格式(Rich Text Format)即RTF格式,又称多文本格式,是由微软公司开发的跨平台文档格式。大多数的文字处理软件都能读取和保存RTF文档。

  • RichText参数

    RichText参数 类型 说明
    overflow TextOverflow 对不可见文本操作
    TextOverflow.ellipsis 以…显示不可见文本
    TextOverflow.visible 只显示能看到的
    TextOverflow.clip 减掉溢出文本(默认)
    TextOverflow.fade 将溢出的文本淡入透明。
    maxLines int 用来设置最大行数
    textAlign TextAlign 对齐属性
    textScaleFactor double 文字放大缩小倍数
    textDirection TextDirection 文本排列方式
    TextDirection.rtl文本从右到左
    TextDirection.ltr文本从左到右
    text TextSpan 必传参数,用来展示文本
    recognizer TapGestureRecognizer 手势监听
  • 使用案例

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    //协议说明文案
    String userPrivateProtocol =
    "我们一向尊重并会严格保护用户在使用本产品时的合法权益(包括用户隐私、用户数据等)不受到任何侵犯。本协议(包括本文最后部分的隐私政策)是用户(包括通过各种合法途径获取到本产品的自然人、法人或其他组织机构,以下简称“用户”或“您”)与我们之间针对本产品相关事项最终的、完整的且排他的协议,并取代、合并之前的当事人之间关于上述事项的讨论和协议。本协议将对用户使用本产品的行为产生法律约束力,您已承诺和保证有权利和能力订立本协议。用户开始使用本产品将视为已经接受本协议,请认真阅读并理解本协议中各种条款,包括免除和限制我们的免责条款和对用户的权利限制(未成年人审阅时应由法定监护人陪同),如果您不能接受本协议中的全部条款,请勿开始使用本产品";

    Widget buildContent(BuildContext context) {
    return Container(
    //ListView可滑动
    child: RichText(
    //必传文本
    text: new TextSpan(
    text: "请认真阅读并理解",
    style: TextStyle(color: Colors.grey),
    //手势监听
    // recognizer: ,
    children: [
    TextSpan(text: "<用户协议>",style: TextStyle(color: Colors.blueAccent),),
    TextSpan(text: "与",style: TextStyle(color: Colors.grey),),
    TextSpan(text: "<隐私协议>",style: TextStyle(color: Colors.blueAccent),),
    TextSpan(text: userPrivateProtocol,style: TextStyle(color: Colors.grey),)
    ]),
    ),
    );
    }

5. 按钮

  • Material 组件库中提供了多种按钮组件:不同的Button拥有不同的功能,它们都有如下共同属性

    1. 按下时都会有“水波动画”

    2. 有一个onPressed属性来设置点击回调,当按钮按下时会执行该回调,如果不提供该回调则按钮会处于禁用状态

    Button 含义
    MaterialButton 默认按钮,扁平,背景透明。按下后,会有背景色。
    RaisedButton
    ElevatedButton 1.22
    “漂浮”按钮,带有阴影和背景。按下后,阴影会变大。
    1.22 后对应主题ElevatedButtonTheme
    FlatButton
    TextButton 1.22
    扁平按钮,默认背景透明。按下后,会有背景色,与MaterialButton一致。
    1.22 后对应主题TextButtonTheme
    IconButton 图标按钮,只能是纯图标,按钮不可展示文案。
    FloatingActionButton 浮动按钮,可显示文字和图标,二者选其一。
    OutlineButton
    OutlinedButton 1.22
    外边框按钮,可设置按钮外边框颜色。
    1.22 后对应主题OutlinedButtonTheme
    ButtonBar 水平布局的按钮容器,可放置多个Button或Text。
    lButton.icon() 带图标文字混合按钮,RaisedButton、FlatButton、OutlineButton都有一个icon 构造函数,
    它可以轻松创建带图标和文字的按钮。

    注:1.22后调整了3个按钮:想要将以前的按钮调整为统一的外观比较麻烦,因此以前经常使用自定义的按钮,而新增的按钮解决了此类问题,可以非常方便的设置整体外观。

  • 按钮使用案例

    1. MaterialButton:默认按钮,扁平,背景透明。按下后,会有背景色。

      1
      2
      3
      4
      new MaterialButton(
      child: new Text('MaterialButton'),
      onPressed: () {},
      ),
    2. ElevatedButton:”漂浮”按钮,带有阴影和背景。按下后,阴影会变大。也是应用最常见的按钮。

      1
      2
      3
      4
      new ElevatedButton(
      child: new Text('RaisedButton'),
      onPressed: () {},
      ),
    3. TextButton:扁平按钮,默认背景透明。按下后,会有背景色,与MaterialButton一致。

      1
      2
      3
      4
      new TextButton(
      child: new Text('FlatButton'),
      onPressed: () {},
      ),
    4. IconButton:图标按钮,只能是纯图标,按钮不可展示文案。

      1
      2
      3
      4
      5
      new IconButton(
      icon: new Icon(Icons.wifi),
      tooltip: 'click IconButton',
      onPressed: () {},
      ),
    5. FloatingActionButton:浮动按钮,可显示文字和图标,二者选其一。可在页面通过设置floatingActionButton来指定页面悬浮按钮,默认在右下角。

      1
      2
      3
      4
      5
      6
      7
      8
      9
      appBar: AppBar(
      title: new Text("按钮控件"),
      ),
      floatingActionButton: new FloatingActionButton(
      child: new Icon(Icons.add_a_photo),
      // child: new Text('FloatingActionButton'),
      tooltip: 'click FloatingActionButton',
      onPressed: () {},
      ),
    6. OutlinedButton:外边框按钮,可设置按钮外边框颜色。

      1
      2
      3
      4
      5
      OutlinedButton(
      child: Text("OutlineButton"),
      borderSide: new BorderSide(color: Colors.pink),
      onPressed: () {},
      ),
    7. ButtonBar:水平布局的按钮容器,可放置多个Button或Text。

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      new ButtonBar(
      children: <Widget>[
      new BackButton(),
      new CloseButton(),
      new Text('ButtonBar组件'),
      new RaisedButton(
      child: new Text('Button'),
      onPressed: () {},
      ),
      ],
      ),
    8. Button.icon:带图标文字混合按钮,RaisedButton、FlatButton、OutlineButton都有一个icon 构造函数,它可以轻松创建带图标和文字的按钮。

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      RaisedButton.icon(
      icon: Icon(Icons.send),
      label: Text("发送"),
      onPressed: () {},
      ),
      OutlineButton.icon(
      icon: Icon(Icons.add),
      label: Text("添加"),
      onPressed: () {},
      ),
      FlatButton.icon(
      icon: Icon(Icons.info),
      label: Text("详情"),
      onPressed: () {},
      ),
    9. 自定义Button样式

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      FlatButton(
      color: Colors.blue,
      highlightColor: Colors.blue[700],
      colorBrightness: Brightness.dark,
      splashColor: Colors.grey,
      child: Text("Submit"),
      shape: RoundedRectangleBorder(
      borderRadius: BorderRadius.circular(20.0)),
      onPressed: () {},
      )

6. 图片:Image

  • Image组件构造函数:Image的数据源可以是asset、文件、内存以及网络。Image 组件有多种构造函数

    构造函数 说明
    new Image 从 ImageProvider 获取图像
    new Image.asset 加载资源图片
    new Image.file 加载本地图片文件
    new Image.network 加 载网络图片
    new Image.memory 加载 Uint8List 资源图片
  • Image组件常见属性

    属性名 类型 说明
    image ImageProvider 抽象类,需要自己实现获取图片数据的操作
    width/height double Image 显示区域的宽度和高度设置,这里需要把 Image 和图片两 个东西区分开,图片本身有大小, Image Widget 是图片的容器,本 身也有大小。 宽度和高度的配置经常和 fit 属性配合使用
    fit BoxFit 图片填充模式 ,
    - Boxfit.fill=会拉伸填充满显示空间
    - Boxfit.contain=在保证图片本身长宽比不变的情况下缩放以适应当前显示空间
    - Boxfit.cover=按图片的长宽比放大后居中填满显示空间,超出显示空间部分会被剪裁。
    - BoxFit.fitWidth=图片的宽度会缩放到显示空间的宽度,高度会按比例缩放
    - BoxFit.fitHeight= 图片的高度会缩放到显示空间的高度,宽度会按比例缩放
    - Boxfit.none=图片没有适应策略,会在显示空间内显示图片
    - BoxFit.scaleDown=效果和 Boxfit.contain差不多但是此属性不允许显示超过源图片大小,即可小不可大
    color Color 图片颜色
    colorBlendMode BlendMode 在对图片进行手动处理的时候,可能用到图层混合,如改变图片的颜色。 此属性可以对颜色进行混合处理。 有多种模式
    alignment Alignment 控制图片的摆放位置,比如l图片放置在右下角则为 Alignment. bottomRight
    repeat ImageRepeat 此属性可以设置图片重复模式 。 noRepeat 为不重复, Repeat 为 x 和 y 方向重复, repeatX 为 x 方向重复, repeatY 为 y 方向重复
    centerSlice Rect 当图片需要被拉伸显示时, centerSIice 定义的矩形区域会被拉仰 , 可以理解成我们在图片内部定义 一个点 9 个点文件用作拉伸, 9个 点为“上” “下 ” “左”“右”“上中”“下 中 ”“左中”“右中 ” “正中”
    matchTextDirection bool matchTextDirection 与 Directionality 配合使用。 TextDirection 有两个值分别为: TextDirection.ltr 从左向右展示图片, TextDirection.rtl 从右向左展示图片
    gaplessPlayback bool 当 lmageProvider 发生变化后 , 重新加载图片的过程中 , 原图片的展示是否保留 。 值为 true 则保留;值为 false 则不保留, 直接空 白等待下一张图片加载
    • ImageProvider:是一个抽象类,主要定义了图片数据获取的接口 load(),从不同的数据源获取图片需要实现不同的 ImageProvider ,如 AssetImage 是实现了从 Asset 中加载图片的 ImageProvider,而 NetworkImage 实现了从网络加载图片的 ImageProvider。

    • asset 图片资源配置

      1. 在工程根目录下创建一个 images 目录,并将图片拷贝到该目录。

      2. 在 pubspec.yaml 中的 flutter 部分添加如下内容

        1
        2
        3
        4
        5
         
        flutter:
        assets:
        - images/a_dot_burr.jpeg
        - images/a_dot_ham.jpeg
      3. 加载图片

        1
        2
        3
        4
        Image.asset(
        "images/avatar.png",
        width: 100.0,
        )
    • network网络图片加载

      1
      2
      3
      4
      Image.network(
      "https://avatars2.githubusercontent.com/u/20411648?s=460&v=4",
      width: 100.0,
      )

4.2 表单组件

1. 文本框:TextField

  • TextField是一个material design风格的输入框,也是属性最多、功能点最多的Widget。

    TextField属性 类型 说明
    controller TextEditingController 绑定输入框预设内容
    获取输入框输入内容
    监听输入框输入和焦点变化
    focusNode
    decoration InputDecoration 输入框样式设置
    keyboardType TextField成为焦点时显示的键盘类型
    - TextInputType.text(普通完整键盘)
    - TextInputType.number(数字键盘)
    - TextInputType.emailAddress(带有“@”的普通键盘)
    - TextInputType.datetime(带有“/”和“:”的数字键盘)
    - TextInputType.multiline(带有选项以启用有符号和十进制模式的数字键盘)
    textInputAction TextInputAction 更改键盘本身的操作按钮
    textCapitalization TextCapitalization 何使输入字母大写的选项。
    - TextCapitalization.sentences-每个句子的首字母大写
    - TextCapitalization.characters:大写句子中的所有字符
    - TextCapitalization.words : 将每个单词的首字母大写
    style TextStyle 输入的文本样式
    strutStyle
    textAlign TextAlign 本币对齐方式
    textAlignVertical
    textDirection
    readOnly bool 是否只读,只读表示不可编辑
    toolbarOptions ToolbarOptions
    showCursor
    autofocus bool 是否自动获得焦点,如果有多个以第一个为准
    obscuringCharacter
    obscureText bool 是否是密码框
    autocorrect
    smartDashesType SmartDashesType
    smartQuotesType SmartQuotesType
    enableSuggestions bool
    maxLines int 输入框的最大行数
    minLines int 输入框的最小行数
    expands bool
    maxLength int 输入框可输入字符数
    maxLengthEnforcement
    onChanged 输入框内容改变时候回调
    onEditingComplete
    onSubmitted 内容提交(按回车)的回调
    onAppPrivateCommand
    inputFormatters
    enabled 是否启用,不启用会置灰
    cursorWidth int 输入框光标快宽度
    cursorHeight int 输入框光标快高度
    cursorRadius Radius 输入框光标圆角半径
    cursorColor Colors 输入框光标颜色
    selectionHeightStyle ui.BoxHeightStyle
    selectionWidthStyle ui.BoxWidthStyle
    keyboardAppearance
    scrollPadding EdgeInsets
    dragStartBehavior DragStartBehavior
    enableInteractiveSelection bool
    selectionControls
    onTap
    mouseCursor
    buildCounter
    scrollController
    scrollPhysics
    autofillHints
    clipBehavior
    restorationId Clip
    enableIMEPersonalizedLearning bool
    • Controller

      1. 初始化Controller

        1
        2
        3
        4
        5
        6
        7
        8
        // 初始化空的Controller
        TextEditingController _editingController = new TextEditingController();
        // 初始化Controller并设置text属性作为输入框默认值
        TextEditingController _controller2 = new TextEditingController(text: "初始化的");
        // 监听输入框
        controller.addListener(() {
        // TODO _editingController.text获取内容
        });
      2. 根据Controller获取输入框的内容

        1
        _editingController.text
      3. 修改输入框中的内容

        1
        _editingController.text = <新内容>;
      4. 清除输入框中内容

        1
        2
        3
        _editingController.text = "";
        ///或者使用clear方法
        _editingController.clear();
  • InputDecoration是输入框装饰器

    InputDecoration属性 类型 说明
    icon Icon 左侧外的图标
    iconColor Color 图标颜色
    label
    labelText 悬浮提示,可代替hintText
    labelStyle 悬浮提示文字的样式
    floatingLabelStyle
    helperText
    helperStyle
    helperMaxLines
    hintText 输入提示
    hintStyle 输入提示样式
    hintTextDirection
    hintMaxLines
    errorText 错误提示
    errorStyle 错误提示样式
    errorMaxLines
    floatingLabelBehavior
    isCollapsed bool
    isDense
    contentPadding
    prefixIcon Icon 左侧内的图标
    prefixIconColor Color 左侧内的图标颜色
    prefixIconConstraints
    prefix 左侧组件
    prefixText 左侧内的文字
    prefixStyle 左侧内的文字样式
    suffix 右侧组件:和suffixText不能同时存在
    suffixText 右侧提示:和suffix不能同时存在
    suffixStyle 右侧提示样式
    suffixIcon 右侧内图标
    suffixIconColor 右侧内图标颜色
    suffixIconConstraints
    counter 自定义计数器
    counterText 计数文字
    counterStyle 计数文字
    filled 是否填充
    fillColor 填充颜色
    focusColor 输入框获取焦点时颜色
    hoverColor 鼠标覆盖时候输入框颜色
    errorBorder 发生错误时候边框颜色
    focusedBorder 获取焦点时候边框颜色
    focusedErrorBorder
    disabledBorder 不可用时候边框
    enabledBorder 启用时编译
    border 边框
    enabled 是否启用
    semanticCounterText
    alignLabelWithHint
    constraints

2. 单选:Radio

  • Radio属性

    Radio属性 类型 说明
    value T 单选的值
    groupValue String 选择组的值,单选组使用同一个状态对象
    onChanged 改变时触发回调
    mouseCursor 鼠标光标
    toggleable bool
    activeColor Color 选中时填充颜色
    fillColor Color
    focusColor Color 聚焦颜色
    hoverColor Color 悬停颜色
    overlayColor
    splashRadius
    materialTapTargetSize 内边距,默认最小点击区域为 48 * 48
    visualDensity
    focusNode
    autofocus bool 自动聚焦,默认为 false

3. 单选列表:RadioListTile

  • RadioListTile属性

    RadioListTile属性 属性 说明
    value
    groupValue
    onChanged
    toggleable
    activeColor
    title
    subtitle
    isThreeLine bool
    dense
    secondary
    selected
    controlAffinity ListTileControlAffinity
    autofocus bool
    contentPadding
    shape
    tileColor
    selectedTileColor
    visualDensity
    focusNode
    enableFeedback

4. 复选:Checkbox

  • Checkbox属性

    Checkbox属性 类型 说明
    value
    onChanged
    tristate
    mouseCursor
    activeColor
    fillColor
    checkColor
    focusColor
    hoverColor
    overlayColor
    splashRadius
    materialTapTargetSize
    visualDensity
    focusNode
    autofocus bool
    shape
    side

5. 下拉选:DropdownButton

  • DropdownButton属性

    DropdownButton属性 类型 说明
    items DropdownMenuItem 下拉选项列表
    onChanged 选择 item 回调
    selectedItemBuilder 选项 item 构造器
    value T 选中内容
    hint 启动状态下默认内容
    disabledHint 禁用状态下默认内容
    elevation 阴影高度
    style 选项列表 item 样式
    underline 按钮下划线
    icon 下拉按钮图标
    iconDisabledColor 禁用状态下图标颜色
    iconEnabledColor 启动时图标颜色
    iconSize 图标尺寸
    isDense 是否降低按钮高度
    isExpanded 是否将下拉列表内容设置水平填充
  • DropdownMenuItem属性

    DropdownMenuItem属性 类型 说明
    value T 对应选中状态内容
    child Widget 下拉列表 item 内容

6. 进度条:*ProgressIndicator

  • 条形进度条:LinearProgressIndicator

    属性 类型 说明
    value double
    backgroundColor Color
    Color Color
    valueColor Animation<Color?>
    minHeight
    semanticsLabel String
    semanticsValue String
  • 环形进度条:CircularProgressIndicator

    属性 类型 说明
    value double
    backgroundColor Color
    color Color
    valueColor Animation<Color?>
    strokeWidth
    semanticsLabel String
    semanticsValue String
  • Slider:滑动进度条

7. 日历

  • 日期时间转换相关API

    1
    2
    3
    4
    5
    6
    7
    8
    // 获取当前时间
    DateTime.now();

    // 获取当前时间的时间戳
    DateTime.now().microsecondsSinceEpoch;

    // 把时间戳转为为日期对象
    DateTime.fromMicrosecondsSinceEpoch(1641950846731362);
  • 第三方包(date_fromat)API:日期格式化

    1. 添加第三方包依赖:date_format

      1
      flutter pub add date_format
    2. 引入第三方包

      1
      import 'package:date_format/date_format.dart';
    3. date_format相关API

      1
      2
      // 根据指定格式格式化日期对象
      formatDate(DateTime(1989, 02, 21), [yyyy, '-', mm, '-', dd]);
  • Flutter自带的日历组件:showDatePicker(返回Future异步结果)

    showDatePicker 属性 类型 说明
    context BuildContext 组件上下文
    initialDate DateTime 默认选中的时间
    firstDate DateTime 日历时间上限
    lastDate DateTime 日历时间下限
    currentDate DateTime
    initialEntryMode DatePickerEntryMode
    selectableDayPredicate SelectableDayPredicate
    helpText String
    cancelText String
    confirmText String
    Locale locale
    useRootNavigator bool
    routeSettings RouteSettings
    textDirection TextDirection
    builder TransitionBuilder
    initialDatePickerMode DatePickerMode
    errorFormatText String
    errorInvalidText String
    fieldHintText String
    fieldLabelText String
  • Flutter自带的时间组件:showTimePicker(返回Future异步结果)

    showTimePicker属性 类型 说明
    context BuildContext
    initialTime TimeOfDay
    builder TransitionBuilder
    useRootNavigator bool
    initialEntryMode TimePickerEntryMode
    cancelText String
    confirmText String
    helpText String
    errorInvalidText String
    hourLabelText String
    minuteLabelText String
    routeSettings RouteSettings
    onEntryModeChanged EntryModeChangeCallback

9. 第三方日历

  • 下载第三方日历:flutter_datetime_picker

    1
    flutter pub add date_time_picker
  • 引入组件

    1
    import 'package:date_time_picker/date_time_picker.dart';

10. 表单:Form

11. 表格

4.3 其他

  1. TabBar
  2. TabBarView
  3. TabController
  4. AlterDialog
  5. SimpleDialog
  6. Divider
  7. Chip
  8. Opacity
  9. ReorderableListView

第五章 容器组件

        容器组件是根据Widget功能方便学习而总结的,Flutter官方未指定什么是容器组件。容器组件主要功能是在布局中添加页面上内容的组件,容器类Widget一般只需要接收一个子Widget(child),他们直接或间接继承自(或包含)SingleChildRenderObjectWidget。并对其添加一些修饰(补白或背景色等)、变换(旋转或剪裁等)、或限制(大小等)。

5.1 内边距

1. Padding

  • Padding:可以给其子节点添加填充(留白),和边距效果类似

    Padding属性 类型 说明
    padding EdgeInsetsGeometry 是一个抽象类,开发中,我们一般都使用EdgeInsets
    child Widget
  • EdgeInsets使用说明

    1
    2
    3
    4
    5
    6
    7
    8
    // 分别指定四个方向的填充。
    EdgeInsets.fromLTRB(double left, double top, double right, double bottom);
    // 所有方向均使用相同数值的填充
    EdgeInsets.all(double value);
    // 设置具体某个方向的填充(可以同时指定多个方向)
    EdgeInsets.only({left, top, right ,bottom });
    // 用于设置对称方向的填充,vertical指top和bottom,horizontal指left和right。
    EdgeInsets.symmetric({ vertical, horizontal })

2. SafeArea

  • SafeArea属性

    SafeArea属性 类型 说明
    left bool
    top bool
    right bool
    bottom bool
    minimum EdgeInsets
    maintainBottomViewPadding bool

5.2 容器尺寸

1. ConstrainedBox

  • ConstrainedBox:用于对子控件添加额外的约束

    ConstrainedBox属性 类型 说明
    constraints BoxConstraints 对子组件的宽高的限制
    - minWidth:最小宽度
    - maxWidth:最大宽度
    - minHeight:最小高度
    - maxHeight:最大高度
    child Widget 子组件
  • 案例代码

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    class Body extends StatelessWidget {
    const Body({Key? key}) : super(key: key);

    @override
    Widget build(BuildContext context) {
    return Center(
    child: Container(
    width: 300,
    height: 400,
    decoration: BoxDecoration(border: Border.all()),
    //利用UnconstrainedBox 消除之前限制
    child: UnconstrainedBox(
    // 对child进行约束,
    child: ConstrainedBox(
    constraints: const BoxConstraints(
    minHeight: 30,
    minWidth: 30,
    maxHeight: 150,
    maxWidth: 150),
    // 子组件最大不会大于被约束的高度
    child: Container(
    width: 310,
    height: 310,
    decoration: BoxDecoration(
    borderRadius: BorderRadius.circular(20),
    gradient: const LinearGradient(
    colors: [Colors.blue, Colors.purple]),
    ),
    ))),
    ),
    );
    }
    }

2. UnconstrainedBox

  • UnconstrainedBox作用对 child 不添加任何约束,允许他以 “自然”大小进行渲染。

    属性 类型 说明
    child
    textDirection
    alignment Alignment
    constrainedAxis
    clipBehavior Clip

3. SizedBox

  • SizedBox两种用法:一是可用来设置两个widget之间的间距,二是可以用来限制子组件的大小。

    属性 类型 说明
    width 宽度
    height 高度
    child Widget 子组件

4. AspectRatio

  • AspectRatio纵横比:作用是根据父元素的设置调整子元素child的宽高比,宽高比是相对父容器的,子元素的宽是父容器的宽,高是根据指定的比例计算出来的

    属性 类型 说明
    aspectRatio double 宽/高
    child Widget 子元素

5. LimtedBox

  • LimtedBox:一个当其自身不受约束时才限制其大小的盒子

    属性 类型 说明
    maxWidth double 最大宽度
    maxHeight double 最大高度
    child Widget 子元素

6. FractionallySizedBox

  • FittedBox:用法与SizedBox类似,只不过FractionallySizedBox的宽高是百分比大小,widthFactor,heightFactor参数就是相对于父控件的比例。注意设置FractionallySizedBox宽高后,其子组件设置的宽高将不起作用

    属性 类型 说明
    alignment Alignment
    widthFactor 宽度百分比
    heightFactor 高度百分比
    child Widget

7. Align

  • Align:可以调整子组件的位置,并且可以根据子组件的宽高来确定自身的的宽高,根据是两个缩放因子,会分别乘以子元素的宽、高,最终的结果就是Align 组件的宽高

    属性 类型 说明
    alignment Alignment 子组件在父组件中的起始位置
    widthFactor 确定Align 组件本身高的属性
    heightFactor 确定Align 组件本身宽的属性
    child Widget 子组件

5.3 容器装饰

  1. DecoratedBox

    • DecoratedBox是个抽象类,具体实现使用BoxDecoration组件,可以给child增加显示效果,如颜色,阴影,边框等

      属性 类型 说明
      color Color 颜色
      image DecorationImage 图片
      border BoxBorder 边框
      borderRadius BorderRadiusGeometry 圆角
      boxShadow List<BoxShadow> 阴影,可以指定多个
      gradient Gradient 渐变
      backgroundBlendMode BlendMode 背景混合模式
      shape BoxShape 形状

5.4 容器变形

Transform

AnimatedPadding

RotateBox

5.5 剪裁

  • ClipOval
  • ClipRRect
  • ClipRect
  • ClipPath
  • CustomClipper

5.6 其他

  1. Container
  2. Center
  3. OverflowBox
  4. SizedOverflowBox

第六章 布局组件

5.Row(横向排布)
6.Column(纵向排布)
7.Expanded和Flexible
8.Stack和Positioned(层叠布局)
10.RefreshIndicator和ListView(下拉刷新)
20.Card(卡片式布局)

Widget 说明 用途
LeafRenderObjectWidget 非容器类组件基类 Widget树的叶子节点,用于没有子节点的widget,通常基础组件都属于这一类,如Image。
SingleChildRenderObjectWidget 单子组件基类 包含一个子Widget,如:ConstrainedBox、DecoratedBox等
MultiChildRenderObjectWidget 多子组件基类 包含多个子Widget,一般都有一个children参数,接受一个Widget数组。如Row、Column、Stack等

尺寸限制类容器用于限制容器大小,Flutter中提供了多种这样的容器,如ConstrainedBoxSizedBoxUnconstrainedBoxAspectRatio 等,本节将介绍一些常用的。

所谓线性布局,即指沿水平或垂直方向排列子组件。Flutter 中通过RowColumn来实现线性布局,类似于Android 中的LinearLayout控件。RowColumn都继承自Flex,我们将在弹性布局一节中详细介绍Flex

弹性布局(Flex)Wrap

Flow

Stack、Positioned

Align

Alignment

FractionalOffset

Center

LayoutBuilder、AfterLayout

第七章 滚动组件

  • 列表:ListView
  • 列表:GridView

第八章 功能组件

第九章 事件与通知

14.PageView(滑动视图)
22.LinearGradient(颜色渐变)
24. GestureDetector(手势监控)
26.(透明度)
27.MediaQuery.removePadding(去除组件之间空格)
29.(拖拽排序组件)

第十章 动画

第十一章 自定义组件

第十二章 文件操作与网络请求

第十三章 国际化

第十四章 Flutter核心原理

第十五章 Flutter项目总结

打赏
  • 版权声明: 本博客所有文章除特别声明外,均采用 Apache License 2.0 许可协议。转载请注明出处!
  • © 2020-2022 xiaoliuxuesheng
  • PV: UV:

老板,来一杯Java

支付宝
微信