目录
  • 1. 概述
  • 2. 常用组件
    • 2.1 text
      • 2.1.1 textstyle
      • 2.1.2 textspan
      • 2.1.3 defaulttextstyle
      • 2.1.4 使用字体
    • 2.2 button
      • 2.2.1 elevatedbutton
      • 2.2.2 textbutton
      • 2.2.3 outlinedbutton
      • 2.2.4 iconbutton
      • 2.2.5 带图标的按钮
    • 2.3 图片及icon
      • 2.3.1 图片
      • 2.3.2 icon
    • 2.4 单选开关和复选框
      • 2.4.1 属性
    • 2.5 输入框以及表单
      • 2.5.1 输入框 textfield
      • 2.5.2 表单

1. 概述

上一篇说到,basics widget 并不是 flutter 的一个专门的widget类别,而是 flutter 官方挑选一些开发常用的 widget 构成的,希望我们掌握到一些最基本的开发能力。

包括:

  • 文本 text
  • 按钮 button
  • 图片 image
  • 单选框、复选框
  • 输入框、表单
  • 指示器
  • container

2. 常用组件

2.1 text

text 用于显示简单样式文本,然后可以填充一些文本显示样式的属性,如下例子:

text("hello world",
        textalign: textalign.left,
        maxlines: 1,
        overflow: textoverflow.ellipsis,
        textscalefactor: 1.5);
  • textalign
    文本对齐方式
  • maxlinesoverflow
    maxlines 指定文本显示的最大行数。
    当文本内容超过最大行数时, overflow 指定了阶段方式, 例如 ellipsis 就是将多余的文本用 “…” 表示
  • textscalefactor
    代表文本相对于当前字体大小的缩放因子,想你对于去设置文本的样式 style 属性的 fontsize, 它是调整字体大小的一个快捷方式, 该属性的默认值可以通过 mediaquerydata.textscalefactor 获得, 如果没有 mediaquery,那么会默认值为 1.0

2.1.1 textstyle

textstyle 用于指定文本样式,例如颜色、字体、粗细、背景等,如下:

  @override
  widget build(buildcontext context) {
    return materialapp(
        title: "flutter",
        home: scaffold(
            appbar: appbar(
              title: const text("basics widget"),
            ),
            body: text(
              "hello world",
              style: textstyle(
                  color: colors.blue,
                  fontsize: 19.0,
                  height: 2,
                  fontfamily: "courier",
                  background: paint()..color = colors.yellow,
                  decoration: textdecoration.underline,
                  decorationstyle: textdecorationstyle.dashed),
            )));
  }

效果如图:

一些属性:

  • height
    行高,它不是一个绝定的值,因为具体的行高为 height*fontsize ,同理行宽也是
  • fontfamily
    由于不同平台默认支持的字体集不同,所以在手动指定字体时一定要先在不同平台测试一下
  • fontsize
    改属性和 text 的 textscalefactor 都用于控制字体大小,但是有两个区别,
    ①:fontsize 可以精确指定字体大小, 而 textscalefactor 只能缩放比例
    ②: textscalefactor 主要是用于系统字体大小设置改变时,对flutter 应用字体进行全局调整,而 fontszie通常用于单个文本,字体大小不会跟随系统字体大小变化

2.1.2 textspan

如果我们需要对text内容不同部分按照不同的样式显示,就可以使用 textspan,代表文本的一个“片段”,看看 textspan的定义:

  const textspan({
    this.text,
    this.children,
    textstyle? style,
    this.recognizer,
    mousecursor? mousecursor,
    this.onenter,
    this.onexit,
    this.semanticslabel,
    this.locale,
    this.spellout,
  })

其中 styletext 代表样式和文本内容, children是 list<inlinespan>? 类型,也就说 textspan 可以包含其他 span

reconizer 用于表示该文本片段上用于手势进行识别处理,下面我们看一个效果图,然后用 textspan 来实现:

body: const text.rich(textspan(children: [
              textspan(text: "home: "),
              textspan(
                text: "https://flutterchina.club",
                style: textstyle(color: colors.blue),
                recognizer: _recognizer
              ),
            ]))));

这里的代码,用 textspan实现了一个基础文本和一个链接片段

  • text.rich 方法将 textspan 添加到 text 中,之所以可以这样做,是因为 text 其实就是 richtext 的一个包装,而 richtext 是可以显示多种多样的 widget
  • _reconizer 是点击链接的处理器

2.1.3 defaulttextstyle

在 widget 树中, 文本的样式默认是可以被继承的,因此如果 widget树的某一个节点处设置一个默认的文本样式,那么该节点的子树所有的文本都会默认使用这个样式,而 defaulttextstyle 正是用于设置默认文本样式的,看下面例子:

defaulttextstyle(
  //1.设置文本默认样式  
  style: textstyle(
    color:colors.red,
    fontsize: 20.0,
  ),
  textalign: textalign.start,
  child: column(
    crossaxisalignment: crossaxisalignment.start,
    children: <widget>[
      text("hello world"),
      text("i am jack"),
      text("i am jack",
        style: textstyle(
          inherit: false, //2.不继承默认样式
          color: colors.grey
        ),
      ),
    ],
  ),
);

这里的代码首先设置了一个默认的样式,字体大小为20,、颜色为红色,然后将 defaulttextstyle 设置给了子树,这样一来 column 所有子孙 text 默认都会继承该样式, 除非 text 设置 inherit: false,如下所示:

2.1.4 使用字体

在 flutter 中可以使用自定义的字体,或者其他第三方字体, 这里就不介绍配置了,具体可以看官方文档:字体

2.2 button

material 组件库提供了多种多样的按钮,他们都是直接或间接对 rawmaterialbutton 的包装定制,所以大部分属性都一样。另外 marterial 库中的按钮都有以下共同点:

  • 按下时都有水波纹
  • 动画统一用 onpressed 属性来设置回调,当按钮按下时会执行该回调,如果不提供回调则按钮会处于禁用状态,不会响应用户点击

2.2.1 elevatedbutton

即 带阴影的按钮, 默认带有阴影和灰色背景,按下后阴影会变大,如下所示:

代码如下:

        child: elevatedbutton(
          child: const text("i am elevatedbutton"),
          onpressed: () {},
        ),
      ),

2.2.2 textbutton

文本按钮,按下后会有背景色,如下图所示:

2.2.3 outlinedbutton

默认有一个边框,不带阴影且背景透明,按下后,边框颜色会变亮、同时出现背景和阴影,如下图所示:

2.2.4 iconbutton

可以点击的 icon, 不包含文字,点击后会出现背景,如下所示:

代码设置为:

iconbutton(
 icon: icon(icons.eleven_mp),
 onpressed: () {},
),

2.2.5 带图标的按钮

上面学到的 elevatedbuttontextbuttonoutlinedbutton 都有一个 icon() 的构造函数,这样就可以代入一个图片进去,例如设置:

elevatedbutton.icon(
          icon: const icon(icons.send),
          label: const text("发送"),
          onpressed: () {},
        ),

效果为(这里有编码问题,可以无视):

2.3 图片及icon

2.3.1 图片

可以通过 image 组件来加载并显示布局, image 的数据源可以是

  • asset
  • 文件
  • 内存
  • 网络
2.3.1.1 imageprovider

imageprovider 是抽象类,主要定义了图片的获取接口 load(),从不同的数据源获取图片需要实现不同的 imageprovider,如 assetimage 是实现了从 asset 中加载图片, networkimage 则实现了从网络中加载图片。

2.3.1.2 image widget

image 组件在构建时有一个必选的 image 参数,它对应一个 imageprovier,下面分别演示一下如何从 asset 和 网络中加载图片。

1.从 asset 中加载图片

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

接下来在 pubspec.yaml 文件的 flutter部分 中,写入(注意缩进):

flutter:
  ..
  assets:
    - assets/images/bobo.jpg

最后在代码中使用:

image(
  image: assetimage("images/bobo.jpg"),
  width: 100.0,
)

就能展示图片。

(不过我这里遇到一个问题,使用手机运行flutter应用能正常展示图片,但是使用 chrome 模拟器会报错,不知道是什么原因造成的

2.从网络url中加载图片

直接使用代码:

image(
  image: networkimage("https://www.wahaotu.com/uploads/allimg/201904/1554901831804910.jpg"),
  width: 100.0,
)

可以正常展示图片。

(不过这里出现了很上面一样的问题,但是使用官方使用的url又能正常展示图片

2.3.1.3 image 参数

我们可以来看下 image 的参数,通过这些参数可以控制图片外观、大小、混合效果等。

  const image({
    key? key,
    required this.image,
    this.framebuilder,
    this.loadingbuilder,
    this.errorbuilder,
    this.semanticlabel,
    this.excludefromsemantics = false,
    this.width,
    this.height,
    this.color,
    this.opacity,
    this.colorblendmode,
    this.fit,
    this.alignment = alignment.center,
    this.repeat = imagerepeat.norepeat,
    this.centerslice,
    this.matchtextdirection = false,
    this.gaplessplayback = false,
    this.isantialias = false,
    this.filterquality = filterquality.low,
  })
  • widthheight
    设置图片宽高,当不指定宽高时,会根据当前父容器的限制尽可能的显示其原始大小,如果只设置其中一个,那么另一个属性默认会按比例缩放
  • fit
    该属性用于用于在图片的显示空间和图片本身大小不同时指定图片的适应模式。适应模式是在 boxfit 中定义的,它是一个枚举类型,有这些值:
    fill:拉伸填充满显示空间 ,图片会便是
    cover:会按图片的长宽比放大后居中填满显示空间,图片不会变形,超出显示部分会被剪裁
    contain:图片默认适应规则,图片会保证图片本身长宽比不变的情况下缩放以适应当前的显示空间
    fitwidth:图片宽度会缩放到显示空间的宽度,高度会按比例缩放,居中显示,图片不会变形
    fitheight:和上面的反着来
  • none:图片没有适应策略,会在显示空间内显示图片

  • colorcolorblendmode:在图片绘制时可以对每一个像素进行颜色混合处理,color指定混合色,而 colorblendmode 指定混合模式下,因为用的比较少,这里就不做实例
  • repeat:当图片本身大小小于显示空间时,指定图片的重复规则,这里也不做展示

2.3.2 icon

android中有 svg 矢量图, 而 flutter 中的也有,就是 icon,它有下面这些优点:

  • 体积小
  • 因为是矢量图,所以拉伸不会影响清晰程度
  • 可以通过 textspan 和 文本混用
  • 可以引用到文本样式

flutter 默认实现了一套icon,在 pubspec.yaml 的配置文件可以看到:

flutter:
  uses-material-design: true

来看下官方的示例代码:

string icons = "";
// accessible: 0xe03e
icons += "\ue03e";
// error:  0xe237
icons += " \ue237";
// fingerprint: 0xe287
icons += " \ue287";

text(
  icons,
  style: textstyle(
    fontfamily: "materialicons",
    fontsize: 24.0,
    color: colors.green,
  ),
);

效果为:

为了不让开发者码点,flutter 封装了 icondataicon来专门显示字体图片,上面的例子也可以用下面方式实现:

row(
  mainaxisalignment: mainaxisalignment.center,
  children: <widget>[
    icon(icons.accessible,color: colors.green),
    icon(icons.error,color: colors.green),
    icon(icons.fingerprint,color: colors.green),
  ],
)

我们也可以使用自定义的字体图标,这里就不赘述了,可以看看官方示例:icon自定义字体图标

2.4 单选开关和复选框

flutter 提供了 material 风格的 开关switch复选框checkbox,它们都继承自 statfulwidget,但是它们不会保存选中的状态,选中状态是由父组件来管理的。 当 switch 或者 checkbox 被点击时,会触发 onchanged 回调,我们可以在此回调中处理选中状态改变逻辑,下面看官方例子:

class switchandcheckboxtestroute extends statefulwidget {
  @override
  _switchandcheckboxtestroutestate createstate() => _switchandcheckboxtestroutestate();
}

class _switchandcheckboxtestroutestate extends state<switchandcheckboxtestroute> {
  bool _switchselected=true; //维护单选开关状态
  bool _checkboxselected=true;//维护复选框状态
  @override
  widget build(buildcontext context) {
    return column(
      children: <widget>[
        switch(
          value: _switchselected,//当前状态
          onchanged:(value){
            //重新构建页面  
            setstate(() {
              _switchselected=value;
            });
          },
        ),
        checkbox(
          value: _checkboxselected,
          activecolor: colors.red, //选中时的颜色
          onchanged:(value){
            setstate(() {
              _checkboxselected=value!;
            });
          } ,
        )
      ],
    );
  }
}

代码中需要维护 switchcheckbox 的选中状态,所以 widget 继承自 statefulwidget。 在其 build 方法中分别状态了 switch 和 checkbox, 并且用两个 bool 值来维护分别的选中状态。 当按钮被点击时,会回调 onchanged 回调选中状态出去,此时我们需要调用 setstate() 方法来触发 flutter 重绘。

为什么要这样子设计,我的理解是:

  • 将开关、复选框的状态抛给父组件,可以更加灵活,比如在勾选时候做一些网络请求,即异步的操作
  • 一般来说,这些item是否选中,是和用户数据关联的,用户数据也不可能是他们的私有状态,所以放在一起管理更好

2.4.1 属性

它们的属性比较简单,常用的有:

  • activecolor:设置激活状态的颜色
  • tristate: 是否为三态,仅 checbox有,一般情况下只有 “true” 和 “false”,表示选中和非选中,如果设置了 tristate 后,还会增加一个 “null” 状态

此外, checkbox 不可设置宽高,其大小是自定义的,而 switch 也仅能设置宽度而已。

2.5 输入框以及表单

flutter material组件提供了 输入款textfield表单form

2.5.1 输入框 textfield

2.5.1.1 属性

来看下 textfield 提供的属性:

  const textfield({
    ...
    this.controller,
    this.focusnode,
    this.decoration = const inputdecoration(),
    textinputtype? keyboardtype,
    this.textinputaction,
    this.textcapitalization = textcapitalization.none,
    this.style,
    this.strutstyle,
    this.textalign = textalign.start,
    this.textalignvertical,
    this.textdirection,
    this.readonly = false,
    toolbaroptions? toolbaroptions,
    this.showcursor,
    this.autofocus = false,
    this.obscuringcharacter = '•',
    this.obscuretext = false,
    this.autocorrect = true,
    smartdashestype? smartdashestype,
    smartquotestype? smartquotestype,
    this.enablesuggestions = true,
    this.maxlines = 1,
    this.minlines,
    this.expands = false,
    this.maxlength,
    this.maxlengthenforcement,
    this.onchanged,
    this.oneditingcomplete,
    this.onsubmitted,
    this.onappprivatecommand,
    this.inputformatters,
    this.enabled,
    this.cursorwidth = 2.0,
    this.cursorheight,
    this.cursorradius,
    this.cursorcolor,
    this.selectionheightstyle = ui.boxheightstyle.tight,
    this.selectionwidthstyle = ui.boxwidthstyle.tight,
    this.keyboardappearance,
    this.scrollpadding = const edgeinsets.all(20.0),
    this.dragstartbehavior = dragstartbehavior.start,
    this.enableinteractiveselection = true,
    this.selectioncontrols,
    this.ontap,
    this.mousecursor,
    this.buildcounter,
    this.scrollcontroller,
    this.scrollphysics,
    this.autofillhints,
    this.restorationid,
    this.enableimepersonalizedlearning = true,
  })

属性比较多,列几个关键的讲解:

  • controller
    编辑框的控制器,通过它可以设置/获取编辑框的内容、选择编辑内容、监听编辑文本改变事件。大多数情况下我们都需要显示提供一个 controller 来与文本框交互,如果设置的话, textfield 内部会创建一个
  • focusnode
    用于控制 textfield 是否占有当前键盘的输入焦点
  • inputdecoration
    用于控制 textfield 的外观显示,如提示文本、背景颜色、边框等。
  • keyboardtype
    用于设置该输入框默认的键盘输入类型, 有文本、电话、email等格式
  • textinputaction
    键盘动作按钮图标,就是右下角的那个图标设置
  • style
    文本的样式(正在编辑中的)
  • textalign
    输入框内编辑文本在水平方向的对齐方式
  • autofocus
    是否自动获取焦点
  • obscuretext
    是否隐藏正在编辑的文本, 比如输入密码的场景,文本内容会用 “•” 来代替
  • maxlines
    最大行数
  • maxlenthmaxlengthenforcement
    maxlenth 代表输入框文本的最大长度,设置后输入框右下角会显示输入的文本计数
    maxlengthenforcement 决定输入文本长度超过 maxlength 时如何处理,如截断
  • toolbaroptions
    长按时出现的菜单,可以选择 copy、cut、paste 、selectall
  • onchange
    输入框内容改变的回调, 当然 controller 也可以做到监听
  • oneditingcompleteonsubmitted
    作用一样,都是在输入完成时触发,比如点击了键盘的 完成键、搜索键不同的是两个回调签名不同
  • inputformatters
    指定输入格式,当用户输入内容改变时,会根据指定格式来校验
  • enable
    如果为false, 则输入框会被禁用
  • cursorwidthcursorradiuscursorcolor
    分别表示自定义输入框光标宽度、圆角和颜色

一个简单的设置代码如下:

column(children: const <widget>[
        textfield(
          autofocus: true,
          decoration: inputdecoration(
            labeltext: "用户名",
            hinttext: "请输入用户名或密码",
            prefixicon: icon(icons.person)
          ),
        ),
        textfield(
          decoration: inputdecoration(
            labeltext: "密码",
            hinttext: "请输入密码",
            prefixicon: icon(icons.lock)
          ),
          obscuretext: true,
        )
      ]),

2.5.1.2 通过 controller 获取输入内容

我们可以通过 onchange 拿到内容。 当然也可以使用 controller 来获取

步骤为:

定义一个 controller
final texteditingcontroller _tfcontroller = texteditingcontroller();
然后在 textfiled 中传入这个 controller
textfield(
  controller: _tfcontroller,
  ...
)

最后就可以通过 : print(_tfcontroller.text) 来获得输入框的内容

2.5.1.3 通过 controller 监听文本内容变化

可以通过 onchange 来监听文本, controller 可以通过设置监听器来监听文本,如下:

  @override
  void initstate() {
    super.initstate();
    _tfcontroller.addlistener(() { 
      print(_tfcontroller.text);
    });
  }

controller 的功能更多,除了监听文本,还可以设置默认值、选择文本等,这里就不多赘述。

2.5.1.4 控制焦点

可以使用 focusnodefocusscopenode 来控制焦点。默认情况下是由 focusscope 来管理,可以在这个范围内通过 focusscopenode 在输入框之间移动焦点、设置默认焦点。

我们可以通过下面代码来获取当前 widget 树中默认的 focusscopenode:

focusscopenode = focusscope.of(context)

拿到句柄后,可以使用下面代码来获取焦点:

focusscopenode.requestfocus(focusnode);

其中 focucsnode 是为 textfield 创建的 focusnode, 这个操作可以让该 textfield 获取焦点。 调用 focusnode.unfocus() 可以取消焦点。

2.5.1.5 监听焦点状态改变事件

通过 focusnode 可以监听焦点改变的事件:

focusnode.addlistener((){
   print(focusnode.hasfocus);
})

true为获取焦点,false为失去焦点

2.5.2 表单

表单form 对输入框进行分组和统一操作。 就像 android 的原生组件 radiogroup 之于 radiobutton 一样, form 可以管理内容校验、输入框重置等。

form 继承自 statefulwidget,其状态管理在 formstate 里面,来看看 from 的定义:

class form extends statefulwidget {
  const form({
    key? key,
    required this.child,
    @deprecated(
      'use autovalidatemode parameter which provides more specific '
      'behavior related to auto validation. '
      'this feature was deprecated after v1.19.0.',
    )
    this.autovalidate = false,
    this.onwillpop,
    this.onchanged,
    autovalidatemode? autovalidatemode,
  })
  ...
  • autovalidate
    是否自动校验输入内容,当为true时,每一个 formfield 内容发生变化时都会校验合法性,并直接显示错误信息,否则就需要通过调用 formstate.validate() 来手动校验
    v1.19 已经废弃了,改成使用 autovalidatemode
  • autovalidatemode
    自动校验模式,是上面的替换,它有三个枚举值:
    disable:当 formfield 内容改变时不做校验
    always:即使用户没有用户交互也要校验合法性
    onuserinteraction:只有在用户交互时才会去校验合法性
  • onwillpop
    决定 form 所在的路由是否可以直接返回。该回调返回一个 future 对象,如果 future 的最终结果是 false,则当前路由不会返回,如果为 true,则会返回到上一个路由。
    这个属性通常是用于拦截返回按钮的
  • onchanged
    form 的任意一个 formfield 内容发生改变时就会调用该方法
2.5.2.1 formfield

form 的子孙元素是 formfield 类型,formfield 是一个抽象类,定义了几个属性, formstate 内部通过他们来完成操作, formfield 部分定义如下:

  const formfield({
    key? key,
    required this.builder,
    this.onsaved,
    this.validator,
    this.initialvalue,
    @deprecated(
      'use autovalidatemode parameter which provides more specific '
      'behavior related to auto validation. '
      'this feature was deprecated after v1.19.0.',
    )
    this.autovalidate = false,
    this.enabled = true,
    autovalidatemode? autovalidatemode,
    this.restorationid,
  })
  • onsaved
    保存时的回调
  • validator
    验证合法性的回调
  • initvalue
    初始值

为了方便使用, flutter 提供了一个 textformfild 组件,继承自 formfield 类,还包装了 textfileld ,可以直接当成 form 的 formfield 来使用, 相当于用 form 来管理 textfield

2.5.2.2 formstate

form 表单的状态类就是 formstate, 可以通过 form.of 或者 globalkey 获得,通过获得它来对 form 的子孙 formfield 进行统一操作。

formstate 常用的三个方法:

  • formstate.validate():调用此方法后, 会调用 form 子孙 formfield.validate() 回调,如果有一个检验失败,那么会返回 false,这样所有校验失败的 widget 都会给出错误提示
  • formstate.save():调用此方法后,会调用 子孙的 formfild.save() 回调,用于保存表单内容
  • formstate.reset(): 会将子孙 formfield 的内容清空
2.5.2.3 示例

我们做一个用户登录的程序,再点击登录前需要做到输入检查:

  • 用户名不能为空,如果为空则提示“用户名不能为空”
  • 密码不能小于6位,如果小于6位则提示 “密码不能少于6位”

代码如下:

import 'package:flutter/material.dart';

class formtestroute extends statefulwidget {
  const formtestroute({key? key}) : super(key: key);

  @override
  state<statefulwidget> createstate() => _formtestroutestate();
}

class _formtestroutestate extends state<formtestroute> {
  final texteditingcontroller _usernamecontroller = texteditingcontroller();
  final texteditingcontroller _passwordcontroller = texteditingcontroller();
  final globalkey _formkey = globalkey<formstate>();

  @override
  widget build(buildcontext context) {
    return scaffold(
        appbar: appbar(
          title: const text('form demo'),
        ),
        body: form(
            key: _formkey,
            autovalidatemode: autovalidatemode.onuserinteraction,
            child: column(
              children: [
                textformfield(
                  autofocus: true,
                  controller: _usernamecontroller,
                  decoration: const inputdecoration(
                      labeltext: "username",
                      hinttext: "username or email",
                      icon: icon(icons.person)),
                  validator: (username) {
                    return username!.trim().isnotempty
                        ? null
                        : "username cannot empty";
                  },
                ),
                textformfield(
                  controller: _passwordcontroller,
                  decoration: const inputdecoration(
                      labeltext: "password",
                      hinttext: "please input your password",
                      icon: icon(icons.lock)),
                  obscuretext: true,
                  validator: (pwd) {
                    return pwd!.trim().length >= 6
                        ? null
                        : "password digit cannot less than 6!";
                  },
                ),
                // login button
                padding(
                  padding: const edgeinsets.only(top: 28.0),
                  child: row(
                    children: [
                      expanded(
                          child: elevatedbutton(
                        onpressed: () {
                          if ((_formkey.currentstate as formstate).validate()) {
                            print("loing success");
                          }
                        },
                        child: const padding(
                          padding: edgeinsets.all(16.0),
                          child: text("login"),
                        ),
                      ))
                    ],
                  ),
                )
              ],
            )));
  }
}

效果如下图所示:

以上所述是www.887551.com给大家介绍的flutter基本组件basics widget学习,希望对大家有所帮助。在此也非常感谢大家对www.887551.com网站的支持!