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

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 fontFamilyFallback,
    double fontSize,
    FontWeight fontWeight,
    FontStyle fontStyle,
    double letterSpacing,
    double wordSpacing,
    TextBaseline textBaseline,
    double height,
    Locale locale,
    Paint foreground,
    Paint background,
    List shadows,
    TextDecoration decoration,
    Color decorationColor,
    TextDecorationStyle decorationStyle,
    double decorationThickness,
    String debugLabel,
  })

你可能感兴趣的:(flutter)