颤振google_fonts包中的字体是否自动存储在缓存中?



我正在阅读google_fonts文档,我主要是为了澄清。

"使用google_fonts包,.ttf或.otf文件不需要存储在您的资产文件夹中并映射到pubspec中。相反,它们可以在运行时通过 http 获取一次,并缓存在应用程序的文件系统中。这是开发的理想选择,并且可能是希望减小应用程序捆绑包大小的生产应用程序的首选行为。

我是否必须遵循额外的步骤来缓存字体,或者假设我使用文档中的以下代码,它应该自动发生:

Text(
'This is Google Fonts',
style: GoogleFonts.lato(),
),

我想我被这里的措辞绊倒了。当它说字体可以在运行时获取一次时,我想知道这是否是默认发生的事情。

我目前正在对自定义字体进行一些字体库研究,以及我在 Google 字体中看到的内容:

https://github.com/material-foundation/google-fonts-flutter/blob/develop/lib/src/google_fonts_variant.dart

看起来很直接,它确实按照代码:

Future<void> saveFontToDeviceFileSystem(String name, List<int> bytes) async {
final file = await _localFile(name);
await file.writeAsBytes(bytes);
}
Future<ByteData> loadFontFromDeviceFileSystem(String name) async {
try {
final file = await _localFile(name);
final fileExists = file.existsSync();
if (fileExists) {
List<int> contents = await file.readAsBytes();
if (contents != null && contents.isNotEmpty) {
return ByteData.view(Uint8List.fromList(contents).buffer);
}
}
} catch (e) {
return null;
}
return null;
}

在运行时,它会签入:

https://github.com/material-foundation/google-fonts-flutter/blob/develop/lib/src/google_fonts_base.dart

Future<void> loadFontIfNecessary(GoogleFontsDescriptor descriptor) async {
final familyWithVariantString = descriptor.familyWithVariant.toString();
final fontName = descriptor.familyWithVariant.toApiFilenamePrefix();
// If this font has already already loaded or is loading, then there is no
// need to attempt to load it again, unless the attempted load results in an
// error.
if (_loadedFonts.contains(familyWithVariantString)) {
return;
} else {
_loadedFonts.add(familyWithVariantString);
}
try {
Future<ByteData> byteData;
// Check if this font can be loaded by the pre-bundled assets.
final assetManifestJson = await assetManifest.json();
final assetPath = _findFamilyWithVariantAssetPath(
descriptor.familyWithVariant,
assetManifestJson,
);
if (assetPath != null) {
byteData = rootBundle.load(assetPath);
}
if (await byteData != null) {
return _loadFontByteData(familyWithVariantString, byteData);
}
// Check if this font can be loaded from the device file system.
byteData = file_io.loadFontFromDeviceFileSystem(familyWithVariantString);
if (await byteData != null) {
return _loadFontByteData(familyWithVariantString, byteData);

虽然它对我不起作用,但它是我正在评估的dynamic_fonts的基础:

https://pub.dev/packages/dynamic_fonts/

不过我同意,措辞并不完全清楚它是否处理缓存,但看起来是按照代码的。

最新更新