Skip to content

Add ability to dynamically load a font #17910

@tvolkert

Description

@tvolkert

We should support dynamically loading a font (e.g. over the network).

Proposed API (in the flutter/services library):

enum FontWeight {
  100,
  200,
  300,
  400,
  500,
  600,
  700,
  800,
  900,
}

enum FontStyle {
  italic,
}

/// A class that enables the dynamic loading of fonts at runtime.
///
/// The [FontLoader] class provides a builder pattern, where the caller builds
/// up the assets that make up a font family, then calls [load] to load the
/// entire font family into a running Flutter application.
class FontLoader {
  /// Creates a new [FontLoader] that will load font assets for the specified
  /// [family].
  ///
  /// The font family will not be available for use until [load] has been
  /// called.
  FontLoader(this.family);

  /// The font family being loaded.
  ///
  /// The family groups a series of related font assets, each of which defines
  /// how to render a specific [FontWeight] and [FontStyle] within the family.
  final String family;

  /// Registers a font asset to be loaded by this font loader.
  ///
  /// The [bytes] argument specifies the actual font asset bytes. Currently,
  /// only TrueType (TTF) fonts are supported.
  ///
  /// The optional [weight] and [style] arguments specify the [FontWeight]
  /// and [FontStyle] to which the asset corresponds, respectively. If they
  /// are unspecified, it signals that this is the default font asset for the
  /// font [family].
  ///
  /// If a font has already been added to this loader that corresponds to the
  /// specified [weight] and [style], a [StateError] will be thrown.
  void addFont(
    Uint8List bytes, {
    FontWeight weight,
    FontStyle style,
  });

  /// Loads this font loader's font [family] and all of its associated assets
  /// into the Flutter engine, making the font available to the current
  /// application.
  ///
  /// This method should only be called once per font loader. Attempts to
  /// load fonts from the same loader more than once will cause a [StateError]
  /// to be thrown.
  Future<void> load();
}

Not only is this something we should have in its own right (it's generally useful to users), but it would enable us to have widget tests that choose to be tied to a specific non-Ahem font, which would be particularly useful in screendiff tests (#17700).

@Hixie

Metadata

Metadata

Assignees

No one assigned

    Labels

    frameworkflutter/packages/flutter repository. See also f: labels.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions