Flutter源码解读

Divider

2022-03-17  本文已影响0人  NetWork小贱

源码解读

// 继承 StatelessWidget 
class Divider extends StatelessWidget {
  /// 创建分割线
  const Divider({
    Key? key,
    this.height,
    this.thickness,
    this.indent,
    this.endIndent,
    this.color,
  }) : assert(height == null || height >= 0.0),
       assert(thickness == null || thickness >= 0.0),
       assert(indent == null || indent >= 0.0),
       assert(endIndent == null || endIndent >= 0.0),
       super(key: key);


  /// 分割线高度范围,如果没有设置,则获取 DividerThemeData.space的值,如果 DividerThemeData.space 也不存在,则默认为 16.
  final double? height;

  /// 分割线内绘制线的粗细
  final double? thickness;

  ///  到分割线前边的空间偏移量
  final double? indent;

  /// 到分割线后边的空间偏移量
  final double? endIndent;

  /// 分割线内绘制线的颜色
  final Color? color;

  /// 通过 connet 生成一个边,可设置颜色和宽度
  static BorderSide createBorderSide(BuildContext? context, { Color? color, double? width }) {
    // 获取有效的颜色
    final Color? effectiveColor = color
        ?? (context != null ? (DividerTheme.of(context).color ?? Theme.of(context).dividerColor) : null);
    // 获取有效的宽度
    final double effectiveWidth =  width
        ?? (context != null ? DividerTheme.of(context).thickness : null)
        ?? 0.0;

    // 如果有效颜色为 null, 则返回只有效宽度的边框边对象,否则返回颜色和宽度都有的对象
    if (effectiveColor == null) {
      return BorderSide(
        width: effectiveWidth,
      );
    }
    return BorderSide(
      color: effectiveColor,
      width: effectiveWidth,
    );
  }
  
  // 重写 StatelessWidget 的 build 方法
  @override
  Widget build(BuildContext context) {
    // 获取分割线主题对象
    final DividerThemeData dividerTheme = DividerTheme.of(context);
    // 分割线的高度空间,默认 16
    final double height = this.height ?? dividerTheme.space ?? 16.0;
    // 分割线内绘制线的粗细
    final double thickness = this.thickness ?? dividerTheme.thickness ?? 0.0;
    // 分割线左右空白间距
    final double indent = this.indent ?? dividerTheme.indent ?? 0.0;
    final double endIndent = this.endIndent ?? dividerTheme.endIndent ?? 0.0;

    return SizedBox(
      height: height, // 设置高度
      child: Center( 
        child: Container(
          height: thickness, 
          margin: EdgeInsetsDirectional.only(start: indent, end: endIndent),
          // Container 的装饰
          decoration: BoxDecoration( 
            border: Border( // 边框对象的底边对象
              bottom: createBorderSide(context, color: color, width: thickness),
            ),
          ),
        ),
      ),
    );
  }
}

二、总结

三、实例

// 基本设置
Divider(
  thickness: 1,
  color: Colors.green,
  indent: 10,
  endIndent: 20,
)

// 通过 context 创建 BorderSide 对象
Border(
  bottom: Divider.createBorderSide(context),
  top: Divider.createBorderSide(context),
)
上一篇下一篇

猜你喜欢

热点阅读