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ı
相关产品推荐
相关产品推荐

