패키지, 저장소 및 앱 카테고리 검색

패키지 상세v3.1.0

dynamic_fonts

Flutter 앱에 동적으로 웹 호스팅된 글꼴을 포함하기 위한 패키지입니다.

AndroidiOSWebmacOSWindowsLinux
30일 다운로드
1.7천
좋아요
52
Pub 점수
160

패키지 설치

flutter pub add dynamic_fonts

패키지 개요

공개 정보를 바탕으로 생성한 선택 가이드입니다.

dynamic_fonts 패키지는 Flutter 애플리케이션에서 런타임에 웹 호스팅된 글꼴을 동적으로 로드하고 사용할 수 있도록 합니다. 앱의 자산에 포함시키지 않고도 사용자 지정 또는 변수 글꼴을 지원해야 하는 앱에 특히 유용합니다. 이 패키지는 URL에서 글꼴을 가져와 글꼴 통합을 단순화하여 간편한 업데이트와 초기 앱 크기 축소를 가능하게 합니다. Android, iOS, Web, macOS, Windows, Linux 등 모든 주요 플랫폼을 지원하므로, 유연한 타이포그래피 솔루션이 필요한 크로스플랫폼 프로젝트에 이상적입니다.

사용 사례

  • 원격 URL에서 글꼴 로드
  • 앱 업데이트 없이 폰트 업데이트
  • 앱 번들 크기 줄이기
  • 변형 폰트 지원
  • 크로스 플랫폼 폰트 일관성

주요 기능

  • 동적 글꼴 로드
  • 원격 글꼴 소스
  • 크로스 플랫폼 호환성
  • 최소 설정
  • 변형 글꼴 지원

적합한 대상

  • 자주 글꼴이 변경되는 앱
  • 웹 우선 플러터 프로젝트
  • 경량 앱 배포
  • 유연성을 필요로 하는 디자인 시스템
  • 여러 글꼴 변형을 관리하는 팀

고려 사항

  • 글꼴 로드를 위해 인터넷 연결이 필요합니다
  • 처음 로드 시 성능에 미치는 잠재적 영향
  • 글꼴 백업은 수동으로 처리해야 합니다
  • 오프라인 전용 앱에는 적합하지 않습니다
  • 캐싱 동작은 플랫폼에 따라 다를 수 있습니다

원본 README

연결된 소스 저장소의 README 원문 스냅샷입니다. 최신 내용은 저장소에서 확인하세요.

dynamic_fonts

The dynamic_fonts package for Flutter allows you to (relatively) easily add dynamically loaded web-hosted fonts to your appーjust like the google_fonts package, but for any arbitrary fonts hosted anywhere.

dynamic_fonts is a fork of google_fonts with more of the API exposed so that you can specify your own fonts.

Why would you use this?

If there is a font that you know you're going to use in your app, just bundle it normally. Don't bother with this package.

But if your app e.g. offers users multiple choices of fonts, and

  1. Some fonts may not be used at all, depending on user preferences
  2. Bundling all of the fonts would bloat your app too much

then this package gives you a convenient way to load your fonts dynamically and keep your initial download slim.

Getting Started

With the dynamic_fonts package, .ttf or .otf files do not need to be stored in your assets folder and mapped in the pubspec. Instead, they can be fetched once via http at runtime, and cached in the app's file system. This is ideal for development, and can be the preferred behavior for production apps that are looking to reduce the app bundle size. Still, you may at any time choose to include the font file in the assets, and the Dynamic Fonts package will prioritize pre-bundled files over http fetching. Because of this, the Dynamic Fonts package allows developers to choose between pre-bundling the fonts and loading them over http, while using the same API.

For example, say you want to use the FiraGO font (not in Google Fonts) in your Flutter app.

First, add the dynamic_fonts package to your pubspec dependencies.

To import DynamicFonts:

import 'package:dynamic_fonts/dynamic_fonts.dart';
Registering a font

To register your font with DynamicFonts, you will need to supply the family name and a map of DynamicFontsVariant to DynamicFontsFile.

  • DynamicFontsVariant merely indicates font weight and font style (normal vs italic)
  • DynamicFontsFile stores checksum info and provides the URL for the file

If we want to download FiraGO from the repo hosted on GitHub (don't do this in a production app!), the URL depends on the variant, so we need to do something like this:

class FiraGoFile extends DynamicFontsFile {
  FiraGoFile(this.variant, String expectedFileHash, int expectedLength)
      : super(expectedFileHash, expectedLength);

  final DynamicFontsVariant variant;

  String get _dir {
    switch (variant.fontStyle) {
      case FontStyle.normal:
        return 'Roman';
      case FontStyle.italic:
        return 'Italic';
    }
    throw Exception('Unknown style: ${variant.fontStyle}');
  }

  @override
  String get url =>
      'https://raw.githubusercontent.com/bBoxType/FiraGO/9882ba0851f88ab904dc237f250db1d45641f45d/Fonts/FiraGO_TTF_1001/$_dir/FiraGO-${variant.toApiFilenamePart()}.ttf';
}

Now we can register the font like so, supplying the SHA256 and file sizes for security. (Actual SHA256 values not shown!)

DynamicFonts.register(
  'FiraGO',
  [
    FiraGoFile(
      const DynamicFontsVariant(
        fontWeight: FontWeight.w400,
        fontStyle: FontStyle.normal,
      ),
      '0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef',
      804888,
    ),
    FiraGoFile(
      const DynamicFontsVariant(
        fontWeight: FontWeight.w700,
        fontStyle: FontStyle.normal,
      ),
      '0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef',
      807140,
    ),
    FiraGoFile(
      const DynamicFontsVariant(
        fontWeight: FontWeight.w400,
        fontStyle: FontStyle.italic,
      ),
      '0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef',
      813116,
    ),
  ].fold<Map<DynamicFontsVariant, DynamicFontsFile>>(
    {},
    (acc, file) => acc..[file.variant] = file,
  ),
);
Using a font

To use DynamicFonts with the default TextStyle:

Text(
  'This is Dynamic Fonts',
  style: DynamicFonts.getFont('FiraGO'),
),

To use DynamicFonts with an existing TextStyle:

Text(
  'This is Dynamic Fonts',
  style: DynamicFonts.getFont(
    'FiraGO', textStyle: TextStyle(color: Colors.blue, letterSpacing: .5),
  ),
),

or

Text(
  'This is Dynamic Fonts',
  style: DynamicFonts.getFont('FiraGO', textStyle: Theme.of(context).textTheme.headline4),
),

To override the fontSize, fontWeight, or fontStyle:

Text(
  'This is Dynamic Fonts',
  style: DynamicFonts.getFont(
    'FiraGO',
    textStyle: Theme.of(context).textTheme.headline4,
    fontSize: 48,
    fontWeight: FontWeight.w700,
    fontStyle: FontStyle.italic,
  ),
),

You can also use DynamicFonts.getTextTheme() to make or modify an entire text theme to use the "FiraGO" font.

MaterialApp(
  theme: ThemeData(
    textTheme: DynamicFonts.getTextTheme(
      'FiraGO',
      Theme.of(context).textTheme,
    ),
  ),
);

Or, if you want a TextTheme where a couple of styles should use a different font:

final textTheme = Theme.of(context).textTheme;

MaterialApp(
  theme: ThemeData(
    textTheme: DynamicFonts.getTextTheme('FiraGO', textTheme).copyWith(
      body1: DynamicFonts.getFont('OtherFont', textStyle: textTheme.body1),
    ),
  ),
);
Bundling font files in your application's assets

The dynamic_fonts package will automatically use matching font files in your pubspec.yaml's assets (rather than fetching them at runtime via HTTP). Once you've settled on the fonts you want to use:

  1. Download the font files from wherever. You only need to download the weights and styles you are using for any given family. Italic styles will include Italic in the filename. Font weights map to file names as follows:
{
  FontWeight.w100: 'Thin',
  FontWeight.w200: 'ExtraLight',
  FontWeight.w300: 'Light',
  FontWeight.w400: 'Regular',
  FontWeight.w500: 'Medium',
  FontWeight.w600: 'SemiBold',
  FontWeight.w700: 'Bold',
  FontWeight.w800: 'ExtraBold',
  FontWeight.w900: 'Black',
}
  1. Move those fonts to a top-level app directory (e.g. dynamic_fonts).

  2. Ensure that you have listed the folder (e.g. dynamic_fonts/) in your pubspec.yaml under assets.

Note: If your fonts' names do not match up with the Google Font naming conventions, you will either have to register them in the fonts section of pubspec.yaml, or rename them.

Licensing Fonts

Be sure to check the licenses of your fonts. For instance FiraGO comes with an OFL.txt file.

Once you've decided on the fonts you want in your published app, you should add the appropriate licenses to your flutter app's LicenseRegistry.

For example:

void main() {
  LicenseRegistry.addLicense(() async* {
    final license = await rootBundle.loadString('dynamic_fonts/OFL.txt');
    yield LicenseEntryWithLineBreaks(['dynamic_fonts'], license);
  });

  runApp(...);
}

카테고리

의존성

의존성 목록 3 개

소스 저장소

이 패키지를 사용하는 프로젝트