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;

猜你喜欢

转载自blog.csdn.net/zy1281539626/article/details/128903654