flutter dynamic cache fonts
flutter dynamic cache fonts

Dynamically cached fonts offer the ability to load and cache any font from any URL as needed. follow this technique helps reduce the bundle size of your application by allowing fonts to be loaded on-demand. By dynamically fetching fonts from external sources you can optimize your web performance and enhance user experience.

Because the font will only need to be downloaded once and used numerous times, caching improves performance while using less network and battery power.

How to Integrate Dynamic Cached Fonts in flutter app

To use the package, add dynamic_cached_fonts as a dependency.

Get started…

Installation.

Step 1): Add this following dependencies project pubspec.yaml file:

dynamic_cached_fonts: ^any

Step 2): Then import it after installing the package using the terminal’s command line:

flutter pub get

Step 3): import the file

import 'package:dynamic_cached_fonts/dynamic_cached_fonts.dart';

Loading the flutter dynamic cached fonts on page…

When a page loads, for instance, you can load a font on demand.

@override
void initState() {
  final DynamicCachedFonts dynamicCachedFont = DynamicCachedFonts(
    fontFamily: fontFamilyName, // The font family name to be passed to TextStyle.fontFamily
    url: fontUrl, // A valid url pointing to a font file (.ttf or .otf files only) 
  );
  dynamicCachedFont.load(); // Downloads the font, caches and loads it.

  super.initState();
}
...
Text(
  'Some Text',
  style: TextStyle(fontFamily: fontFamilyName),
)

Load the font , when button click

onPressed: () {
    final DynamicCachedFonts dynamicCachedFont = DynamicCachedFonts(
      fontFamily: fontFamilyName,
      url: fontUrl,
    );

    dynamicCachedFont.load();
  },

Pass in maxCacheObjects and cacheStalePeriod to alter the size of the cache or perhaps the length of time the font remains in cache.

DynamicCachedFonts(
  fontFamily: fontFamilyName,
  url: fontUrl,
  maxCacheObjects: 150,
  cacheStalePeriod: const Duration(days: 100),
);

TextStyle.fontOnly after load() is called are families applied.

What if you need to load several fonts, each with a different weight and style?The DynamicCachedFonts.family constructor can be used for that.

Incorporating a list of URLs directing users to various fonts within the same family enables the utilization of dynamically cached fonts. This approach allows for the dynamic loading and caching of fonts as required. By leveraging this functionality you can effectively reduce the overall size of your bundle while enabling the loading of fonts ondemand based on specific user needs. This approach enhances performance and optimizes user experience by seamlessly integrating range of fonts from different sources within cohesive font family.

DynamicCachedFonts.family(
  urls: <String>[
    fontFamilyNameBoldUrl,
    fontFamilyNameItalicUrl,
    fontFamilyNameRegularUrl,
    fontFamilyNameThinUrl,
  ],
  fontFamily: fontFamilyName,
);

Make use of the static methods if you require more control!

onPressed: () {
  DynamicCachedFonts.cacheFont(fontUrl);
},

The cacheStalePeriod and maxCacheObjects parameters are also available .

loadCachedFont , loadCached , canLoadFontFamily canTo see if the font is cached use the LoadFont method . It frequently works in tandem with the loadCached methods.

Before attempting to load a font, it is advisable to first check if the font is already cached . By verifying the font’s presence in the cache, you can avoid unnecessary network requests. If the font is indeed cached, you can proceed to activate it, ensuring a swift and seamless rendering of the font. This proactive approach optimizes the font loading process by efficiently utilizing the cached resources, resulting in improved performance and a smoother user experience.

if(DynamicCachedFonts.canLoadFont(fontUrl)) {
  // To load a single font...
  DynamicCachedFonts.loadCachedFont(
    fontUrl,
    fontFamily: fontFamilyName,
  );

  // Or if you want to load multiple fonts as a family...
  DynamicCachedFonts.loadCachedFamily(
    <String>[
      fontFamilyNameBoldUrl,
      fontFamilyNameItalicUrl,
      fontFamilyNameRegularUrl,
      fontFamilyNameThinUrl,
    ],
    fontFamily: fontFamilyName,
  );
}

Now, download the font if it isn’t already there in cache!

if(DynamicCachedFonts.canLoadFont(fontUrl)) {
 /// do code here
} else {
  DynamicCachedFonts.cacheFont(fontUrl);
}

RemoveCachedFont

To extend the functionality of RawDynamicCachedFonts and modify the implementation of static methods including the addition of removeCachedFont to permanently remove a font from the cache.

Do you want to load a specific font from Firebase Cloud Storage? Choose the constructor DynamicCachedFonts.fromFirebase! Google Cloud Storage locations with urls beginning with gs:// are accepted. It is similar to the default constructor aside from that.

This implementation file code is shown here;

import 'package:dynamic_cached_fonts/dynamic_cached_fonts.dart';
import 'package:flutter/material.dart';
import 'constants.dart';
import 'src/components.dart';
import 'src/demos.dart';

void main() {
  DynamicCachedFonts.toggleVerboseLogging(true);

  runApp(
    MaterialApp(
      title: 'Dynamic Cached Fonts Demo',
      home: const DynamicCachedFontsDemo1(),
      darkTheme: ThemeData.dark(),
    ),
  );
}

class DynamicCachedFontsDemo1 extends StatefulWidget {
  const DynamicCachedFontsDemo1({Key? key}) : super(key: key);

  @override
  _DynamicCachedFontsDemo1State createState() => _DynamicCachedFontsDemo1State();
}

class _DynamicCachedFontsDemo1State extends State<DynamicCachedFontsDemo1> {
  @override
  void initState() {
    final DynamicCachedFonts dynamicCachedFont = DynamicCachedFonts(
      fontFamily: cascadiaCode,
      url: cascadiaCodeUrl,
    );
    dynamicCachedFont.load();

    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text(demoTitle),
      ),
      body: const Center(
        child: DisplayText(
          'The text is being displayed in $cascadiaCode which is being dynamically loaded and cached',
          fontFamily: cascadiaCode,
        ),
      ),
      floatingActionButton: ExtendedButton(
        icon: Icons.navigate_next,
        label: 'Next Example',
        onPressed: () => Navigator.push(
          context,
          MaterialPageRoute<DynamicCachedFontsDemo2>(
            builder: (_) => const DynamicCachedFontsDemo2(),
          ),
        ),
      ),
    );
  }
}

For this example code click here Github

Conclusion 👍

While the system fonts on Android and iOS are of a high caliber, designers frequently ask for custom fonts.This is a small example of dynamic cached fonts implemented in flutter , you can modify with your needs..

Thanks for reading this article 💙

Have a good day


Recommended Articles

Flutter Google Font’s Package

How to repair or clean cache of all dependencies in flutter

Icons in flutter – font awesome