Flutter 指定字体(全局指定、局部指定)

该博客介绍了Flutter项目中字体配置的方法。首先需下载字体文件(.ttf或.otf)并放到根目录下的foots文件夹,还给出了字体下载地址。接着说明了在pubspec.yaml中定义字体,以及全局和局部配置字体的方式,也提及可定义公共textStyle。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. 下载字体文件(.ttf 或.otf )放到根目录下的foots文件夹下,如果没有自己创建。

给个字体下载的地址:http://www.diyiziti.com/Download/308

2. 在pubspec.yaml中定义

fonts:
  - family: MaoTi                # 字体别名
    fonts:
      - asset: fonts/mao_ti.ttf  # 字体文件目录
        weight: 700              # 权重 700表示粗体,相当于bold 
  - family: PingFang
    fonts:
      - asset: fonts/ping_fang.ttf

3. 全局配置— 就在主题theme中配置

MaterialApp(
  theme: ThemeData(
      fontFamily: "PingFang", // 统一指定应用的字体。
      primarySwatch: Colors.green,
      primaryColor: Colors.white),
      。。。

4. 局部配置—指定TextStyle中的fontFamily

TextStyle(
    fontFamily:"PingFang", // 指定该Text的字体。
    fontSize: SizeUtil.getFontSize(Dimens.font_sp12),
    color: CustomColors.colorPrimary,
    fontWeight: FontWeight.bold)

5. 如果多处用到指定的字体,但又不是全局用到, 你可以定义一个公共的 textStyle .如:

var textFontStyle  = TextStyle(
    fontFamily:"PingFang", // 指定该Text的字体。
)
 
用到的地方用 .copyWith 这个方法, 如: 
Text(
    "显示我想要的字体",
    style: textFontStyle.copyWith(
        fontSize: 18.0,
        color: Colors.red,
        fontWeight: FontWeight.bold,
        ),
    )

TextStyle的copyWith如下: 

 TextStyle copyWith({
    bool inherit,
    Color color,
    Color backgroundColor,
    String fontFamily,
    List<String> fontFamilyFallback,
    double fontSize,
    FontWeight fontWeight,
    FontStyle fontStyle,
    double letterSpacing,
    double wordSpacing,
    TextBaseline textBaseline,
    double height,
    Locale locale,
    Paint foreground,
    Paint background,
    List<ui.Shadow> shadows,
    TextDecoration decoration,
    Color decorationColor,
    TextDecorationStyle decorationStyle,
    double decorationThickness,
    String debugLabel,
  })
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值