Skip to content
Talk to an engineerRequest access

Styling and fonts

Size and colour, MathTheme, styling parts of a formula, and changing the math font, symbol fallbacks and the fonts of text inside formulas.

A formula’s size and colour come from the ambient DefaultTextStyle, merged with the widget’s textStyle (style on MathSpan and MathText), and the platform text scaler applies on top. A MathTheme colour wins over the text style’s.

const Math.tex(
r'e^{i\pi} + 1 = 0',
textStyle: TextStyle(fontSize: 32, color: Colors.indigo),
)

Formulas follow the platform’s bold-text setting, and in high-contrast mode their colour is drawn fully opaque.

MathTheme sets defaults for every formula below it: colour, error, placeholder and selection colours, the math font and its fallbacks, and styles per \htmlClass name.

MathTheme(
data: const MathThemeData(color: Colors.indigo, errorColor: Colors.orange),
child: child,
)

Latin Modern Math is the default. Any OpenType font with a MATH table can replace it. Load the bytes yourself — for example from an asset declared in your pubspec.yaml:

import 'package:flutter/services.dart';
import 'package:val_latex_flutter/val_latex_flutter.dart';
Future<MathFont> loadMathFont() async {
final data = await rootBundle.load('assets/fonts/MyMathFont.otf');
return MathFont.fromBytes(data.buffer.asUint8List());
}

Pass it to one formula with Math.tex(…, font: font), or to a subtree with MathThemeData(font: font). MathFont.fromBytes throws a FontFormatException when the font has no MATH table. After loading a new font you can empty the shared layouts with MathCache.clear().

  • Variable fonts: MathFont.fromBytes(bytes, variations: {'wght': 700}).
  • Symbol fallbacks: MathFont.symbols(bytes) wraps a font without a MATH table, used only for its glyphs. Pass it in MathThemeData(fallbackFonts: […]). Symbols missing from the math font and the fallbacks come from the bundled STIX Two Math.

Besides the two bundled fonts, the package’s tests lay its formula corpus out in Fira Math, Libertinus Math, Garamond-Math and Noto Sans Math (subsets of them). Other math fonts load through MathFont.fromBytes but have not been tried.

Text inside formulas (\text{…}, \textsf{…}, \texttt{…}, \textsc{…}) is shaped by Flutter’s text engine, so every script your fonts cover shapes correctly — Arabic letters join, Indic clusters form, emoji stay whole. MathTextFonts chooses the families; the default, MathTextFonts.latinModern, uses the Latin Modern text fonts the package bundles.

Field Used for
roman \text, \textrm
sans \textsf
mono \texttt, \verb
smallCaps \textsc
fallback Families tried, in order, for characters the main family lacks; after them, the platform’s fonts.
const formula = Math.tex(
r'\text{المساحة} = \pi r^2',
displayMode: true,
textFonts: MathTextFonts(fallback: ['NotoNaskhArabic']),
);

Family names must be fonts your app declares in its pubspec.yaml, or that the platform provides. textFonts is also a parameter of MathSpan and MathText.

Which fonts text runs (\text{…}, non-math characters) use.

More about MathTextFonts

The defaults are the bundled Latin Modern text fonts, which match the math font. Characters they lack (Arabic, Bengali, CJK, emoji…) fall back to fallback and then to the platform’s fonts.

Constructor Description
MathTextFonts({…}) Creates a font configuration.
MathTextFonts: more
const MathTextFonts({
this.roman = '${_package}LatinModernRoman',
this.sans = '${_package}LatinModernSans',
this.mono = '${_package}LatinModernMono',
this.smallCaps = '${_package}LatinModernRomanCaps',
this.fallback = const [],
})
Field Type Default Description
roman String 'packages/val_latex_flutter/LatinModernRoman' Serif family (\textrm, \text).
sans String 'packages/val_latex_flutter/LatinModernSans' Sans-serif family (\textsf).
mono String 'packages/val_latex_flutter/LatinModernMono' Monospace family (\texttt, \verb).
smallCaps String 'packages/val_latex_flutter/LatinModernRomanCaps' Small-caps family (\textsc).
fallback List<String> const [] Families tried, in order, for characters the main family lacks.
Member Type Description
static latinModern = MathTextFonts() The bundled Latin Modern fonts.
withFallback(List<String> fallback) MathTextFonts A copy with a different fallback list.
styleFor(TextFont font, double size, {Color? color}) TextStyle The Flutter text style for font at size logical pixels.

A math font: an OpenType font with a MATH table, measured in em.

More about MathFont

This is what layout reads. Every length it returns is in em (font units ÷ units per em), so callers multiply by the font size.

A variable font is used at its default instance unless axis values are given (variations, instance): then outlines, advances and text shaping follow them, and so do the MATH table’s constants, italics corrections, top accent attachments and math kerning where the font gives them variation deltas.

Constructor Description
MathFont(font) Wraps a parsed font. Throws if it has no MATH table.
MathFont.fromBytes(Uint8List bytes, {…}) Parses a font file; a variable font at axis variations (tag → value, as in {'wght': 700}; see instance).
MathFont.symbols(Uint8List bytes, {…}) A font used only for its glyphs, as a symbol fallback after the math font (layoutFormula’s fallbackFonts); it needs no MATH table (Noto Sans Symbols, a system symbol font…).
MathFont.symbolsOf(OpenTypeFont font) Wraps a parsed font used only for its glyphs, like MathFont.symbols but without parsing the file again.
MathFont.fromBytes: more
factory MathFont.fromBytes(
Uint8List bytes, {
Map<String, double> variations = const {},
})
MathFont.symbols: more
factory MathFont.symbols(
Uint8List bytes, {
int index = 0,
Map<String, double> variations = const {},
})

From a font collection (.ttc), font index; a variable font at axis variations (see instance), as in MathFont.symbols(bytes, variations: {'wght': 700, 'wdth': 75}).

Field Type Default Description
font OpenTypeFont required The underlying font.
xHeight double x-height in em.
minConnectorOverlap double Minimum connector overlap for assemblies, in em.
Member Type Description
instance(Map<String, double> values) MathFont This font at variation axis values (tag → value in the axis’s own units, as in {'wght': 700}), with its own glyph and metric caches; see OpenTypeFont.instance. Axes left out take their defaults, so values do not add up across calls. The same values give the same object, and the default values (or a font that does not vary) give the default font.
axes List<FontAxis> The variation axes (fvar); empty when the font does not vary.
variations Map<String, double> The axis values this font is at, tag → value, for every axis.
static latinModern MathFont Latin Modern Math, bundled with val_latex (GUST Font License).
static stixTwo MathFont STIX Two Math, bundled with val_latex (SIL Open Font License) as the fallback for symbols Latin Modern Math lacks; decoded the first time one is needed.
name String Family name.
unitsPerEm double Units per em.
em(num fontUnits) double Converts font units to em.
constant(String name) double A MATH constant in em. Percent constants (scriptPercentScaleDown, scriptScriptPercentScaleDown, radicalDegreeBottomRaisePercent) are returned as fractions (0.7).
constants Map<String, double> All constants as returned by constant.
glyph(int codePoint) int The glyph for codePoint, or 0 when the font has none.
scriptVariant(int glyph, int level) int glyph’s script-size form (ssty) for script level 1 (script) or 2 (scriptscript), or glyph when the font has none.
mirroredVariant(int glyph) int? glyph’s right-to-left mirrored form (rtlm), or null.
has(int codePoint) bool Whether the font maps codePoint.
metrics(int glyph) GlyphMetrics Metrics of glyph.
isExtendedShape(int glyph) bool Whether glyph is an extended shape.
kern(int glyph) MathKernInfo? Math kerning for glyph (font units inside), or null.
kernAt(int glyph, MathKernCorner corner, double heightEm) double The kern for a script at heightEm on corner of glyph, in em.
verticalStretch(int glyph) StretchInfo? How glyph grows vertically, or null.
horizontalStretch(int glyph) StretchInfo? How glyph grows horizontally, or null.
outline(int glyph) GlyphPath The outline of glyph, in font units, y up.

Size information for one glyph, in em.

Constructor Description
GlyphMetrics({…}) Creates metrics.
GlyphMetrics: more
const GlyphMetrics({
required this.glyph,
required this.advance,
required this.height,
required this.depth,
required this.left,
required this.right,
required this.italicCorrection,
required this.topAccentAttachment,
})
Field Type Default Description
glyph int required Glyph id.
advance double required Advance width.
height double required Ink extent above the baseline (≥ 0 unless the ink is below it).
depth double required Ink extent below the baseline, positive downwards.
left double required Left edge of the ink (left side bearing).
right double required Right edge of the ink.
italicCorrection double required Italic correction (0 when the font gives none).
topAccentAttachment double required Horizontal position for a top accent (the centre when the font gives none).

A design axis of a variable font (fvar): weight (wght), width (wdth), optical size (opsz)…, in the font’s own user units.

Constructor Description
FontAxis(tag, minValue, defaultValue, maxValue, {…}) Creates an axis.
FontAxis: more
const FontAxis(
this.tag,
this.minValue,
this.defaultValue,
this.maxValue, {
this.name,
this.hidden = false,
})
Field Type Default Description
tag String required Four-character tag.
minValue double required Smallest value.
defaultValue double required Value of the default instance.
maxValue double required Largest value.
name String? Name for people (from the name table), if any.
hidden bool false Whether the font asks for the axis to be hidden from users.

A named instance of a variable font (fvar): “Bold”, “Condensed Light”… and its axis values.

Constructor Description
NamedInstance(name, coordinates) Creates an instance.
Field Type Default Description
name String? required Subfamily name (from the name table), if any.
coordinates Map<String, double> required Axis tag → value, for every axis.