Flutter Widget - Font自定义字体(google_fonts)

0. google_font 字体简介

google_fonts 可以无需在本机存储任何字体文件即可访问1400多种字体

查看搜索字体:https://fonts.google.com/

在这里插入图片描述

1. 安装插件

修改 pubspec.yaml 配置文件添加 google_fonts 插件:

dependencies:
  google_fonts: ^4.0.3

执行 flutter pub get 更新插件。

2. Text文本使用 google_fonts

import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Font 字体组件 - GoogleFonts'),
        ),
        body: Text(
          'Dash is Awesome',
          // style: GoogleFonts.lobster(),
          style: GoogleFonts.lobster(
            textStyle: const TextStyle(
              fontSize: 50
            )
          ),
        )
      )
    );
  }
}

在这里插入图片描述

3. 主题全局设置 font

ThemeData(
	primarySwatch: Colors.blue,
	textTheme: GoogleFonts.lobsterTextTheme(
		Theme.of(context).textTheme
	)
)

// 覆盖 fontSize  fontWeight  fontStyle
Text(
  'This is Google Fonts',
  style: GoogleFonts.lato(
    textStyle: Theme.of(context).textTheme.headline4,
    fontSize: 48,
    fontWeight: FontWeight.w700,
    fontStyle: FontStyle.italic,
  ),
),

4. HTTP 请求字体

google_fonts 会尝试经由HTTP来获取字体,要留意得是在macOS平台上得确认entitlements授权机制中已写入开放网络获取的指令列

<key>com.apple.security.network.client</key>
<true/>

可以将google_fonts的字体文件捆绑到应用静态文件中,完成后便会自动套用字体,因此就无需由HTTP获取了。

  1. 下载字体文件
  2. 将文件移到项目资源目录
    在这里插入图片描述
  3. 修改 pubspec.yaml 添加资源文件夹
    # pubspec.yaml
    assets:
    	- google_fonts/
    

一旦将字体文件捆绑到应用程序文件后,应用程序的主要方法中allowRuntimeFetching 可设置为false 来禁用HTTP字体请求

GoogleFonts.config.allowRuntimeFetching = false;
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

优小U

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值