Dynamic Cached Fonts
A customizable dynamic font loader for flutter with caching enabled. Supports Firebase Cloud Storage too!
Introduction
Dynamic Cached Fonts allows you to dynamically load a font from any url and cache it. This way, you can reduce your bundle size and load the font if and when it's required.
Another advantage of dynamically loading fonts is that you can now easily provide an option to your users to pick an app font. This allows for a greater level of customization.
Caching is an added performance upgrade as the font will be downloaded only once and used multiple times, reducing network and battery usage.
Get Started
To use the package, add dynamic_cached_fonts
as a dependency in your pubspec.yaml file.
Usage
Loading fonts on demand
You can load font on demand, for example - when a page loads
Or a button is clicked
If you want to change the how large the cache can be or maybe how long the font stays in cache, pass in maxCacheObjects
and cacheStalePeriod
.
TextStyle.fontFamily
s are applied only after load()
is called.
Calling
load()
more than once throws aStateError
What if you need to load multiple fonts, of varying weights and styles, as a single family...For that, you can use the DynamicCachedFonts.family
constructor.
It accepts a list of urls, pointing to different fonts in the same family, as urls
.
If you need more control, use the static methods!
cacheFont
You can pass in maxCacheObjects
and cacheStalePeriod
here as well.
canLoadFont
, loadCachedFont
, loadCachedFamily
canLoadFont
is used to check whether the font is available in cache. It is usually used in combination with the loaders.
First, Check whether the font is already in cache. If it is, then load the font.
Now, if the font isn't available in cache, download it.
removeCachedFont
To remove a font from cache permanently, use removeCachedFont
.
Note - This does not change the font immediately until a complete app restart.
Finally, if you want to customize their implementation, extend RawDynamicCachedFonts
and override the static methods.
Have a custom font to load from Firebase Cloud Storage? Go for the DynamicCachedFonts.fromFirebase
constructor! It accepts a Google Cloud Storage location which is a url starting with gs://
. Other than that, it is similar to the default constructor.
Tip: Every method, except
load()
, has a parameter namedverboseLog
which is used to log detailed statuses and configurations for debugging.