You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter自定义TextStyle子类如何设置固定默认阴影参数实现样式复用?

解决方案

Dart中构造函数的可选参数默认值必须为编译时常量,你只需要给目标阴影数组添加const修饰,直接作为shadows参数的默认值即可。

实现代码(支持自定义覆盖阴影)

如果需要保留外部自定义阴影的能力,使用如下实现:

import 'dart:ui' show Offset, Shadow;
import 'package:flutter/painting.dart' show TextStyle, Color, FontWeight;

class ShadowTextStyle extends TextStyle {
  const ShadowTextStyle({
    required Color color,
    required FontWeight fontWeight,
    double size = 14,
    // 直接设置const修饰的阴影数组为默认值
    List<Shadow>? shadows = const <Shadow>[
      Shadow(
        offset: Offset(1.0, 0.0),
        blurRadius: 5.0,
        color: Color.fromARGB(255, 0, 0, 0),
      ),
    ],
  }) : super(
          color: color,
          fontWeight: fontWeight,
          fontSize: size,
          shadows: shadows,
        );
}

实现代码(强制固定阴影,不允许修改)

如果你希望所有ShadowTextStyle实例都强制使用你定义的阴影配置,不允许外部修改,可以直接把阴影参数写在父类初始化逻辑中,去掉构造函数的shadows参数:

import 'dart:ui' show Offset, Shadow;
import 'package:flutter/painting.dart' show TextStyle, Color, FontWeight;

class ShadowTextStyle extends TextStyle {
  const ShadowTextStyle({
    required Color color,
    required FontWeight fontWeight,
    double size = 14,
  }) : super(
          color: color,
          fontWeight: fontWeight,
          fontSize: size,
          shadows: const <Shadow>[
            Shadow(
              offset: Offset(1.0, 0.0),
              blurRadius: 5.0,
              color: Color.fromARGB(255, 0, 0, 0),
            ),
          ],
        );
}

使用示例

Text(
  '测试阴影文本',
  style: ShadowTextStyle(
    color: const Color(0xFFFFFFFF),
    fontWeight: FontWeight.w600,
    size: 18,
    // 不需要自定义阴影时可以省略该参数,自动使用默认配置
    // shadows: [], // 传空数组即可去掉阴影
  ),
)

内容的提问来源于stack exchange,提问作者Ismail Muhammad

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 00:24:00