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

Flutter自定义类中添加if语句实现字体加粗功能求助

解决方案

直接在构造函数中通过三元运算符根据bold字段的值动态设置字体权重即可,修改后的完整代码如下:

import 'package:flutter/material.dart';

class myTextStyle extends TextStyle {
  final Color color;
  final double size;
  final String fontFamily;
  final bool bold;

  const myTextStyle({
    required this.size,
    this.color = Colors.black87,
    this.fontFamily = 'OpenSans',
    this.bold = false, // 为bold设置默认值,避免必填
  })  : assert(size != null),
        super(
          color: color,
          fontSize: size,
          fontFamily: fontFamily,
          fontWeight: bold ? FontWeight.bold : null, // 根据bold值判断字体权重
        );
}

关键修改点说明

  • 给bold参数添加默认值false,这样使用该类时无需每次都传入bold参数
  • 在调用父类构造函数时,通过三元运算符实现逻辑:当bold为true时设置fontWeight为FontWeight.bold,否则传入null,继承TextStyle的默认字体权重行为

内容的提问来源于stack exchange,提问作者Şahin Yakıcı

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 15:57:18