flutter - 如何更改现有 TextStyle 的特定属性?

标签 flutter dart

我想制作一个自定义小部件,它基本上通过获取一个文本来为文本添加笔划,将其包装在一个包含两个文本的 Stack 中,其中一个用笔划渲染。

class BorderedText extends StatelessWidget {
  final Text displayText;
  final Color strokeColor;
  final double strokeWidth;

  BorderedText(this.displayText,
      {Key key, this.strokeColor = Colors.black, this.strokeWidth = 1.0})
      : assert(displayText != null),
        super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Stack(
        children: <Widget>[
          Text(
            displayText.data,
            style: displayText.style
              ..foreground = Paint()
                ..style = PaintingStyle.stroke
                ..strokeWidth = strokeWidth
                ..color = strokeColor,
          ),
          displayText,
        ],
      ),
    );
  }
}

预期使用方式:

BorderedText(
  Text(
    "Hello App",
    style: TextStyle(
      color: Colors.white,
      fontSize: 34.0,
      fontFamily: "LexendMega",
    ),
  ),
  strokeWidth: 6.0,
),

遗憾的是,这段代码不起作用,因为 foreground 是最终的。我该如何解决这个问题?

  • 我能否完整复制 displayText 参数并能够更改其 foreground
  • 我可以复制它的 TextStyle,只改变前景吗?

最佳答案

您可以使用 TextStyle.copyWith为了这。这将从您的其他文本样式复制参数,并且仅更改您提供的参数。在您的情况下,它看起来像这样:

Text(
  displayText.data,
  style: displayText.style.copyWith(
      foreground: Paint()
        ..style = PaintingStyle.stroke
        ..strokeWidth = strokeWidth
        ..color = strokeColor
  ),
)

顺便说一下:Flutter 框架中的许多类都存在此方法(在有意义的地方),它非常有用,否则您将需要手动输入所有参数。

关于flutter - 如何更改现有 TextStyle 的特定属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57531166/

相关文章:

flutter - 如何创建动画确定的圆形进度指示器?

关闭并重新打开选项卡时 Flutter web shared_preferences 不可用

dart - Dart中有基本的过期 map 吗?

flutter - 分析使所需的构造函数出错

android - flutter package如何获取Android字符串资源?

flutter - 如何在 Flutter 中使卡片可拖动

收到新事件时,Flutter Bloc 取消正在运行的事件

flutter - 如何解析Flutter中limitToLast返回的DataSnapshot

flutter - 构建FutureBuilder <List <Data >>(脏,状态:_FutureBuilderState <List <Data >>#d53db)时,引发了以下NoSuchMethodError。

android - 在 flutter 插件类中捕获 onNewIntent()