Flutter在线字体加载插件online_font的使用

发布于 1周前 作者 sinazl 来自 Flutter

Flutter在线字体加载插件online_font的使用

在线字体插件online_font

pub package

本插件允许你在Flutter应用中使用在线字体。该插件受到了google_fonts的启发。

使用方法

声明字体家族

你可以像这样声明你的字体家族:

class YujiMai extends OnlineFont {
  const YujiMai();

  [@override](/user/override)
  String get fontFamily => 'YujiMai';

  [@override](/user/override)
  Map<FontVariant, FontFile> get fonts => {
    FontVariant.regular: const FontFile(
      url: 'https://fonts.gstatic.com/s/a/d6741e6df72abe0287210735f84bb297fb8704e9e44ae1bd53e9366f75215ce8.ttf',
      // ---------------可选参数---------------
      expectedFileHash: 'd6741e6df72abe0287210735f84bb297fb8704e9e44ae1bd53e9366f75215ce8',
      expectedLength: 7830152,
      extensionName: 'ttf',
      // ---------------可选参数---------------
    ),
  };
}

或者像这样声明:

final yujiMai = RawOnlineFont(fontFamily: 'YujiMai', fonts: _fonts);

使用字体

你可以像这样使用字体:

Text('Hello, world', style: yujiMai.textStyle());
Text('Hello, world', style: const YujiMai().textStyle());

预加载字体

你可以预加载字体,以便在使用时更快地显示:

await yujiMai.loadAll();

// 然后可以这样使用
const Text('Hello, world', style: TextStyle(fontFamily: 'YujiMai-Regular'));
// 如果不关心`const`,可以使用上述方式
Text('Hello, world', style: yujiMai.textStyle());
Text('Hello, world', style: const YujiMai().textStyle());

你也可以只预加载一种字体样式:

await yujiMai.loadVariant(FontVariant.regular);

完整示例

以下是一个完整的示例,展示了如何在Flutter应用中使用online_font插件:

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

void main() => runApp(const MyApp());

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

  [@override](/user/override)
  Widget build(BuildContext context) => const MaterialApp(home: MyHomePage());
}

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

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: InkWell(
          onTap: () => Navigator.push(
            context,
            MaterialPageRoute(builder: (context) => const PreloadExample()),
          ),
          child: Text(
            '点击预加载示例',
            style: const YujiMai().textStyle(
              fontSize: 20,
              color: Colors.orange,
            ),
          ),
        ),
      ),
    );
  }
}

class PreloadExample extends StatefulWidget {
  const PreloadExample({super.key});

  [@override](/user/override)
  State<PreloadExample> createState() => _PreloadExampleState();
}

class _PreloadExampleState extends State<PreloadExample> {
  [@override](/user/override)
  void initState() {
    super.initState();
    // 调用此方法将返回一个Future,你可以用它来显示加载指示器或其他内容

    // 你不需要调用`setState`,文本会通过`FontLoader`自动刷新
    yujiMai.loadAll();
    // 或者
    // const YujiMai().loadAll();
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: InkWell(
          onTap: () => Navigator.pop(context),
          child: const Text(
            '返回上一页',
            style: TextStyle(fontFamily: 'YujiMai-Regular'),
            // style: TextStyle(
            //   fontFamily: const FontFamilyWithVariant(
            //     family: 'YujiMai',
            //     fontVariant: FontVariant(
            //       fontWeight: FontWeight.w400,
            //       fontStyle: FontStyle.normal,
            //     ),
            //   ).toString(),
            // ),
            // style: yujiMai.textStyle(),
            // style: const YujiMai().textStyle(),
          ),
        ),
      ),
    );
  }
}

final _fonts = {
  FontVariant.regular: const FontFile(
    url:
        'https://fonts.gstatic.com/s/a/d6741e6df72abe0287210735f84bb297fb8704e9e44ae1bd53e9366f75215ce8.ttf',
    expectedFileHash:
        'd6741e6df72abe0287210735f84bb297fb8704e9e44ae1bd53e9366f75215ce8',
    expectedLength: 7830152,
    extensionName: 'ttf',
  ),
};

// 第一种方式
class YujiMai extends OnlineFont {
  const YujiMai();

  [@override](/user/override)
  String get fontFamily => 'YujiMai';

  [@override](/user/override)
  Map<FontVariant, FontFile> get fonts => _fonts;
}

// 第二种方式
final yujiMai = RawOnlineFont(
  fontFamily: 'YujiMai',
  fonts: _fonts,
);

更多关于Flutter在线字体加载插件online_font的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter在线字体加载插件online_font的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,以下是如何在Flutter中使用online_font插件来加载在线字体的一个示例。online_font插件允许你从远程URL加载字体并在Flutter应用中使用它们。请注意,实际使用时你可能需要确保插件的版本是最新的,并查阅最新的官方文档以获取任何更新或变更。

首先,你需要在你的pubspec.yaml文件中添加online_font依赖:

dependencies:
  flutter:
    sdk: flutter
  online_font: ^x.y.z  # 请替换为实际最新版本号

然后运行flutter pub get来安装依赖。

接下来是一个完整的示例代码,展示如何使用online_font插件加载在线字体:

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Online Font Example',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  // 在线字体URL
  final String fontUrl = 'https://example.com/path/to/your/font.woff2'; // 请替换为实际字体URL

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Online Font Example'),
      ),
      body: Center(
        child: FutureBuilder<OnlineFont>(
          future: OnlineFont.load(fontUrl),
          builder: (context, snapshot) {
            if (snapshot.connectionState == ConnectionState.done) {
              if (snapshot.hasError) {
                return Text('Failed to load font: ${snapshot.error}');
              } else {
                final OnlineFont onlineFont = snapshot.data!;
                return Text(
                  'Hello, this is text with online font!',
                  style: TextStyle(
                    fontFamily: onlineFont.fontFamily,
                    fontSize: 24,
                  ),
                );
              }
            } else {
              return CircularProgressIndicator();
            }
          },
        ),
      ),
    );
  }
}

在这个示例中:

  1. fontUrl变量存储了在线字体的URL。你需要将其替换为实际的字体文件URL。
  2. OnlineFont.load(fontUrl)是一个异步操作,它返回一个Future<OnlineFont>对象。
  3. 使用FutureBuilder来处理异步加载,并在加载完成后应用字体。
  4. 如果加载成功,snapshot.data将包含一个OnlineFont对象,你可以通过onlineFont.fontFamily来获取加载的字体族名,并将其应用于TextStyle中。

请确保你的网络请求符合相关的隐私和安全政策,特别是如果你打算在生产环境中使用这个功能。

回到顶部