loadFonts function
- CupertinoFontConfig cupertinoFonts = const CupertinoFontConfig.override(),
Loads fonts and icons required for consistent screenshot rendering.
This function ensures that all fonts (including system fonts) and icons are properly loaded before taking screenshots. It should be called once before running any tests that use snap to ensure consistent text rendering across all screenshots.
Cupertino Fonts
By default, Cupertino system fonts are overridden with Roboto to ensure
consistent rendering across macOS, Linux, and Windows. Pass
cupertinoFonts to customize this behavior:
// Use SF Pro on macOS for visual debugging (not recommended for goldens)
await loadFonts(
cupertinoFonts: CupertinoFontConfig.fromMacOsSystemFonts(),
);
// Use a custom font (must be declared in pubspec.yaml)
await loadFonts(
cupertinoFonts: CupertinoFontConfig.override(fontFamily: 'Inter'),
);
Important: Once fonts are loaded, they cannot be unloaded due to Flutter's limitations. This means that if loadFonts is called during one test, all subsequent tests in the same test run will use the loaded fonts, which may cause text to render differently than in a fresh test environment.
You can work around this limitation by using Snap.golden, instead of matchesGoldenFile, which will block out all text independent of the loaded fonts.
The function is idempotent - calling it multiple times has no additional effect after the first call.
Implementation
Future<void> loadFonts({
CupertinoFontConfig cupertinoFonts = const CupertinoFontConfig.override(),
}) async {
if (_fontsLoaded) return;
TestWidgetsFlutterBinding.ensureInitialized();
await _loadMaterialFontsFromSdk();
await _loadFontsFromFontManifest();
switch (cupertinoFonts) {
case _MacOsCupertinoFonts(
fallbackOverride: final fallbackOverrideFontFamily,
):
try {
await _loadMacOSFonts();
} on _MacOsFontLoadException catch (e) {
if (fallbackOverrideFontFamily == null) {
throw StateError(
'CupertinoFontConfig.fromMacOsSystemFonts() failed: $e\n'
'SF Pro fonts are only available on macOS with the fonts '
'installed from https://developer.apple.com/fonts/.\n'
'To use a fallback font instead, pass '
'fallbackOverrideFontFamily, or use '
'CupertinoFontConfig.override() for cross-platform consistency.',
);
}
if (fallbackOverrideFontFamily == 'Roboto') {
await _overrideCupertinoFontsWithRoboto();
} else {
await _overrideCupertinoFontsWithFamily(
fallbackOverrideFontFamily,
);
}
}
case _OverrideCupertinoFonts(:final fontFamily):
if (fontFamily == 'Roboto') {
await _overrideCupertinoFontsWithRoboto();
} else {
await _overrideCupertinoFontsWithFamily(fontFamily);
}
}
_fontsLoaded = true;
}