Flutter - 常见组件

345 阅读6分钟

Text

用来负责显示文本信息的一个组件,功能类似于 Android 的 TextView、HTML 的一些文本标签等等,属于基础组件。

const Text(
    //要显示的文字内容
    this.data,
   {
    //key类似于id
    Key key,
    //文字显示样式和属性
    this.style,
    this.strutStyle,
    //文字对齐方式
    this.textAlign,
    //文字显示方向
    this.textDirection,
    //设置语言环境
    this.locale,
    //是否自动换行
    this.softWrap,
    //文字溢出后处理方式
    this.overflow,
    //字体缩放
    this.textScaleFactor,
    //最大显示行数
    this.maxLines,
    //图像的语义描述,用于向Andoid上的TalkBack和iOS上的VoiceOver提供图像描述
    this.semanticsLabel,
  })

Text中style属性比较常用,TextStyle对象的大致属性配置

const TextStyle({
    //是否继承父类组件属性
    this.inherit = true,
    //字体颜色
    this.color,
    //文字大小,默认14px
    this.fontSize,
    //字体粗细
    this.fontWeight,
    //字体样式,normal或italic
    this.fontStyle,
    //字母间距,默认为0,负数间距缩小,正数间距增大
    this.letterSpacing,
    //单词间距,默认为0,负数间距缩小,正数间距增大
    this.wordSpacing,
    //字体基线
    this.textBaseline,
    //行高
    this.height,
    //设置区域
    this.locale,
    //前景色
    this.foreground,
    //背景色
    this.background,
    //阴影
    this.shadows,
    //文字划线,下换线等等装饰
    this.decoration,
    //划线颜色
    this.decorationColor,
    //划线样式,虚线、实线等样式
    this.decorationStyle,
    //描述信息
    this.debugLabel,
    //字体
    String fontFamily,
    List<String> fontFamilyFallback,
    String package,
  })

可以在 Text 里加入一些 Span 标签,对某部分文字进行个性化改变样式,如加入 @ 符号,加入超链接、变色、加表情等等。Text.rich(…) 等价于 RichText(...),用哪个都可以。

const Text.rich(
    // 样式片段标签TextSpan
    this.textSpan,
  {
    Key key,
    this.style,
    this.strutStyle,
    this.textAlign,
    this.textDirection,
    this.locale,
    this.softWrap,
    this.overflow,
    this.textScaleFactor,
    this.maxLines,
    this.semanticsLabel,
  })

const RichText({
    Key key,
    // 样式片段标签TextSpan
    @required this.text,
    this.textAlign = TextAlign.start,
    this.textDirection,
    this.softWrap = true,
    this.overflow = TextOverflow.clip,
    this.textScaleFactor = 1.0,
    this.maxLines,
    this.locale,
    this.strutStyle,
  })

textSpan类型是TextSpan,其他参数和上面的一样

const TextSpan({
    //样式片段
    this.style,
    //要显示的文字
    this.text,
    //样式片段TextSpan数组,可以包含多个TextSpan
    this.children,
    //用于手势进行识别处理,如点击跳转
    this.recognizer,
  })

Image

Image 是一个图像的 Widget ,提供了一些类方法来快捷使用来自内存、本地、网络、Assets 的图片。

//通过ImageProvider来加载图片
const Image({
    Key key,
    // ImageProvider,图像显示源
    @required this.image,
    this.semanticLabel,
    this.excludeFromSemantics = false,
    //显示宽度
    this.width,
    //显示高度
    this.height,
    //图片的混合色值
    this.color,
    //混合模式
    this.colorBlendMode,
    //缩放显示模式
    this.fit,
    //对齐方式
    this.alignment = Alignment.center,
    //重复方式
    this.repeat = ImageRepeat.noRepeat,
    //当图片需要被拉伸显示的时候,centerSlice定义的矩形区域会被拉伸,类似.9图片
    this.centerSlice,
    //类似于文字的显示方向
    this.matchTextDirection = false,
    //图片发生变化后,加载过程中原图片保留还是留白
    this.gaplessPlayback = false,
    //图片显示质量
    this.filterQuality = FilterQuality.low,
  })

// 加载网络图片,封装类:NetworkImage
Image.network(
    //路径
    String src,
   {
    Key key,
    //缩放
    double scale = 1.0,
    this.semanticLabel,
    this.excludeFromSemantics = false,
    this.width,
    this.height,
    this.color,
    this.colorBlendMode,
    this.fit,
    this.alignment = Alignment.center,
    this.repeat = ImageRepeat.noRepeat,
    this.centerSlice,
    this.matchTextDirection = false,
    this.gaplessPlayback = false,
    this.filterQuality = FilterQuality.low,
    Map<String, String> headers,
  })

// 加载本地File文件图片,封装类:FileImage
Image.file(
    //File对象
    File file,
  {
    Key key,
    double scale = 1.0,
    this.semanticLabel,
    this.excludeFromSemantics = false,
    this.width,
    this.height,
    this.color,
    this.colorBlendMode,
    this.fit,
    this.alignment = Alignment.center,
    this.repeat = ImageRepeat.noRepeat,
    this.centerSlice,
    this.matchTextDirection = false,
    this.gaplessPlayback = false,
    this.filterQuality = FilterQuality.low,
  })

// 加载本地资源图片,例如项目内资源图片
// 需要把图片路径在pubspec.yaml文件中声明一下,如:
// assets:
//      - packages/fancy_backgrounds/backgrounds/background1.png
// 封装类有:AssetImage、ExactAssetImage
Image.asset(
    //文件名称,包含路径
    String name,
  {
    Key key,
    // 用于访问资源对象
    AssetBundle bundle,
    this.semanticLabel,
    this.excludeFromSemantics = false,
    double scale,
    this.width,
    this.height,
    this.color,
    this.colorBlendMode,
    this.fit,
    this.alignment = Alignment.center,
    this.repeat = ImageRepeat.noRepeat,
    this.centerSlice,
    this.matchTextDirection = false,
    this.gaplessPlayback = false,
    String package,
    this.filterQuality = FilterQuality.low,
  })

// 加载Uint8List资源图片/从内存中获取图片显示
// 封装类:MemoryImage
Image.memory(
    // Uint8List资源图片
    Uint8List bytes,
  {
    Key key,
    double scale = 1.0,
    this.semanticLabel,
    this.excludeFromSemantics = false,
    this.width,
    this.height,
    this.color,
    this.colorBlendMode,
    this.fit,
    this.alignment = Alignment.center,
    this.repeat = ImageRepeat.noRepeat,
    this.centerSlice,
    this.matchTextDirection = false,
    this.gaplessPlayback = false,
    this.filterQuality = FilterQuality.low,
  })
ColorBlendModel 混合参数
enum BlendMode {
  clear,src,dst,srcOver,dstOver,srcIn,dstIn,srcOut,dstOut,srcATop,dstATop,xor,plus,modulate,screen,overlay,darken,lighten,colorDodge,colorBurn,hardLight,softLight,difference,exclusion,multiply,hue,saturation,color,luminosity,
}

image.png

Boxfit枚举定义
  • BoxFit.fill:充满父容器。
  • BoxFit.contain:尽可能大,保持图片分辨率。
  • BoxFit.cover:充满容器,可能会被截断。
  • BoxFit.none:图片居中显示,不改变分大小,可能会被截断。
  • BoxFit.fitWidth:图片填满宽度,高度可能会被截断
  • BoxFit.fitHeight:图片填满高度,宽度可能会被截断
  • BoxFit.scaleDown:图片可以完整显示,但是可能不能填充满。

Image 组件的 image 参数是一个 ImageProvider, 这样的设计好处是你的图片对象可以来自于各种方式

image.png

ImageProvider 是一个抽象类,实现类有 FileImage MemoryImage NetWorkImage

Icon

该组件用来显示可缩放的图标,不会像图片一样失真,还能设置颜色。

const Icon(
    
    // IconData 图标数据
    this.icon, {
    Key? key,
      
    // 尺寸
    this.size,
      
    // 颜色
    this.color,
    
    // 方向
    this.textDirection,
      
    this.semanticLabel,
  }) : super(key: key);

Android的所有图标的地址: fonts.google.com/icons?selec…

image.png IOS的图标需要使用CupertinoIcons对象来访问 api.flutter.dev/flutter/cup…

image.png

ElevatedButton

const ElevatedButton({
    Key? key,
    // 点击事件
    required VoidCallback? onPressed,
    // 长按
    VoidCallback? onLongPress,
    // hover
    ValueChanged<bool>? onHover,
    ValueChanged<bool>? onFocusChange,
    
    // 样式
    ButtonStyle? style,
    
    // 焦点
    FocusNode? focusNode,
    bool autofocus = false,
    Clip clipBehavior = Clip.none,
    
    // 按钮内容
    required Widget? child,
  })

ButtonStyle样式的属性

class ButtonStyle with Diagnosticable {
  /// Create a [ButtonStyle].
  const ButtonStyle({
    // 文字
    this.textStyle,
    // 背景色
    this.backgroundColor,
    // 前景色
    this.foregroundColor,
    // 鼠标滑过颜色
    this.overlayColor,
    // 阴影
    this.shadowColor,
    // 阴影高度
    this.elevation,
    // 内边距
    this.padding,
    // 最小尺寸
    this.minimumSize,
		// 固定 size
    this.fixedSize,
    // 最大最小尺寸
    this.maximumSize,
    // 边框
    this.side,
    // 形状
    this.shape,
    // 鼠标光标
    this.mouseCursor,
    // 紧凑程度
    this.visualDensity,
    // 配置可以按下按钮的区域的尺寸
    this.tapTargetSize,
    // 定义 [shape] 和 [elevation] 的动画更改的持续时间
    this.animationDuration,
    // 检测到的手势是否应该提供声音和/或触觉反馈
    this.enableFeedback,
    // 子元素对齐方式
    this.alignment,
    // 墨水效果
    this.splashFactory,
  });

TextButton

TextButton 文本按钮,默认背景透明并不带阴影。按下后,会有背景色

OutlineButton

默认有一个边框,不带阴影且背景透明。按下后,边框颜色会变亮、同时出现背景和阴影(较弱)

IconButton

是一个可点击的Icon,不包括文字,默认没有背景,点击后会出现背景

TextField

TextField用于文本输入, 有着丰富的属性

const TextField({
    Key? key,
    // 控制器
    this.controller,
    // 焦点管理
    this.focusNode,
    // 装饰器 背景 颜色 边框 ...
    this.decoration = const InputDecoration(),
    // 键盘输入类型
    // text	文本输入键盘
		// multiline	多行文本,需和maxLines配合使用(设为null或大于1)
		// number	数字;会弹出数字键盘
		// phone	优化后的电话号码输入键盘;会弹出数字键盘并显示“* #”
		// datetime	优化后的日期输入键盘;Android上会显示“: -”
		// emailAddress	优化后的电子邮件地址;会显示“@ .”
		// url	优化后的url输入键盘; 会显示“/ .”
    TextInputType? keyboardType,
    // 键盘动作按钮图标
    // TextInputAction.search 搜索
    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,
    // 输入框的最大行数,默认为1;如果为null,则无行数限制。
    this.maxLines = 1,
    this.minLines,
    this.expands = false,
    // 代表输入框文本的最大长度,设置后输入框右下角会显示输入的文本计数。
    this.maxLength,
    @Deprecated(
      'Use maxLengthEnforcement parameter which provides more specific '
      'behavior related to the maxLength limit. '
      'This feature was deprecated after v1.25.0-5.0.pre.',
    )
    this.maxLengthEnforced = true,
    this.maxLengthEnforcement,
    // 输入框内容改变时的回调函数;注:内容改变事件也可以通过controller来监听。
    this.onChanged,
    // 编辑完成
    this.onEditingComplete,
    // 确认输入内容
    this.onSubmitted,
    this.onAppPrivateCommand,
    // 指定输入格式;当用户输入内容改变时,会根据指定的格式来校验。
    this.inputFormatters,
    // 如果为false,则输入框会被禁用,禁用状态不接收输入和事件,同时显示禁用态样式(在其decoration中定义)。
    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 = const <String>[],
    this.clipBehavior = Clip.hardEdge,
    this.restorationId,
    this.enableIMEPersonalizedLearning = true,
  })

GestureDetector

一个用于手势识别的功能性组件,我们通过它可以来识别各种手势。

GestureDetector({
    Key? key,
    this.child,
  	// 单击
    this.onTapDown,
    this.onTapUp,
    this.onTap,
    this.onTapCancel,
  	// 双指
    this.onSecondaryTap,
    this.onSecondaryTapDown,
    this.onSecondaryTapUp,
    this.onSecondaryTapCancel,
  	// 三点
    this.onTertiaryTapDown,
    this.onTertiaryTapUp,
    this.onTertiaryTapCancel,
  	// 双击
    this.onDoubleTapDown,
    this.onDoubleTap,
    this.onDoubleTapCancel,
  	// 长按
    this.onLongPressDown,
    this.onLongPressCancel,
    this.onLongPress,
    this.onLongPressStart,
    this.onLongPressMoveUpdate,
    this.onLongPressUp,
    this.onLongPressEnd,
  	// 两点 三点 长按
    this.onSecondaryLongPressDown,
    this.onSecondaryLongPressCancel,
    this.onSecondaryLongPress,
    this.onSecondaryLongPressStart,
    this.onSecondaryLongPressMoveUpdate,
    this.onSecondaryLongPressUp,
    this.onSecondaryLongPressEnd,
    this.onTertiaryLongPressDown,
    this.onTertiaryLongPressCancel,
    this.onTertiaryLongPress,
    this.onTertiaryLongPressStart,
    this.onTertiaryLongPressMoveUpdate,
    this.onTertiaryLongPressUp,
    this.onTertiaryLongPressEnd,
  	// 垂直 水平 Drag
    this.onVerticalDragDown,
    this.onVerticalDragStart,
    this.onVerticalDragUpdate,
    this.onVerticalDragEnd,
    this.onVerticalDragCancel,
    this.onHorizontalDragDown,
    this.onHorizontalDragStart,
    this.onHorizontalDragUpdate,
    this.onHorizontalDragEnd,
    this.onHorizontalDragCancel,
    this.onForcePressStart,
    this.onForcePressPeak,
    this.onForcePressUpdate,
    this.onForcePressEnd,
  	// 点击滑动
    this.onPanDown,
    this.onPanStart,
    this.onPanUpdate,
    this.onPanEnd,
    this.onPanCancel,
    this.onScaleStart,
    this.onScaleUpdate,
    this.onScaleEnd,
    this.behavior,
    this.excludeFromSemantics = false,
    this.dragStartBehavior = DragStartBehavior.start,

InkWell

带有水波纹效果的组件(点击时)

const InkWell({
    Key? key,
    Widget? child,
    // 点击
    GestureTapCallback? onTap,
    GestureTapCallback? onDoubleTap,
    // 长按
    GestureLongPressCallback? onLongPress,
    GestureTapDownCallback? onTapDown,
    GestureTapCancelCallback? onTapCancel,
    ValueChanged<bool>? onHighlightChanged,
    ValueChanged<bool>? onHover,
    // 光标样式
    MouseCursor? mouseCursor,
    // 颜色
    Color? focusColor,
    Color? hoverColor,
    Color? highlightColor,
    MaterialStateProperty<Color?>? overlayColor,
    Color? splashColor,
    InteractiveInkFeatureFactory? splashFactory,
    double? radius,
    BorderRadius? borderRadius,
    ShapeBorder? customBorder,
    bool? enableFeedback = true,
    bool excludeFromSemantics = false,
    FocusNode? focusNode,
    bool canRequestFocus = true,
    ValueChanged<bool>? onFocusChange,
    bool autofocus = false,
  })

我正在参与掘金技术社区创作者签约计划招募活动,点击链接报名投稿