. How To Write High-Ranking, High-Quality Content in 2024
Flutter

Best practices for optimizing Flutter web loading speed

admin
10 May 2024
Best practices for optimizing Flutter web loading speed
An illustration of excellent practices for enhancing the pace at which Flutter webpages load

As a Flutter developer that collaborates with the Google Flutter team as well as independently in my own time, I am aware of and sympathetic to the worries people have about how slowly Flutter web apps load. Improving loading speed is essential for enhanced functionality and a satisfying user experience, particularly when Flutter developers start working on web applications. This tutorial provides best practices and doable tactics to boost the efficiency of your Flutter web applications.

Rendering

Through the use of WebGL, CanvasKit, the default renderer for Flutter online applications, provides excellent speed and pixel-perfect consistency across platforms. Complex graphical applications requiring high resolution and rich animations will especially benefit from this capabilities. However, CanvasKit’s 1.5 MB default file size may be a disadvantage, particularly for apps where the first load speed is crucial.

All Flutter widgets must wait for CanvasKit and main.dart.js to fully load into the browser, even if the flutter.js load API parallelizes their download. This could cause observable delays before the application becomes interactive. Developers can select the Wasm rendering option to allay these worries and improve the loading experience.

These procedures are for developers who are prepared to experiment with cutting-edge capabilities, as WebAssembly support in Flutter web is considered experimental and subject to change. As features and commands change, it’s important to always check the most recent Flutter documentation for the most up-to-date procedures.

Compatibility

Building with Wasm does not support the dart:html package. Because of this restriction, you need to pay close attention to the APIs that your application uses. As an alternative, dart2wasm and dart2js both support the web package.

Performance

Wasm is faster to start up than JavaScript and not just makes apps smaller than CanvasKit.

Lazy loading

By dividing your code into segments and loading them only when required, you may minimize the initial load time with Dart’s deferred imports. The use of deferred loading is covered in the ensuing sections.

Declare a deferred import

Declare the import you wish to defer at the top of your Dart file. Put “deferred” in your import declaration, followed by an identifier. Use the loadLibrary() function on the deferred import to load the library asynchronously as needed:

				
					import 'package:myapp/hello.dart' deferred as hello;

Future<void> loadHelloLibrary() async {
  await hello.loadLibrary();
  hello.sayHi();
}
				
			

Call the load function

Call this function from time to time in your Flutter application, for instance in reaction to user input. When the user clicks a widget, the example below loads the required library:

				
					import 'package:flutter/material.dart';

void main() {
  runApp(MaterialApp(home: MyApp()));
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: ElevatedButton(
          onPressed: () {
            loadHelloLibrary();
          },
          child: Text('Load Feature'),
        ),
      ),
    );
  }
}
				
			

Unawaited function calls

Try not to wait for expensive futures before using runApp to cut down on the amount of time it takes for your app to display its initial widget. Certain futures don’t need to wait to update the user interface once they’re finished. App programmers can explicitly inform the “unawaited futures” lint that such futures are not anticipated to be awaited by using the unawaited function. This makes the app feel more responsive, which improves the user experience during both app setup and page loading. To prevent problems with resource management and consistency in the app’s state, it’s crucial to handle these features properly.

				
					import 'dart:async';
import 'package:flutter/material.dart';

void main() {
  unawaited(downloadVideos().then(videos) {
    playlist.add(videos);
  });

  runApp(const MyApp());
}
				
			

Media files

Displaying assets at optimal resolution

Using the pixel density of the device as a guide, Flutter loads assets at the proper resolution automatically. This guarantees the best possible images on a range of screen sizes. As we’ll discuss in the next section, while optimizing assets for efficient distribution is crucial, give priority to supplying materials at the precise resolutions required before looking into alternate picture formats.

Better image compression

Two of the most common image formats found on webpages are PNG and JPG. These formats are well known for being widely compatible and supported. On the other hand, cutting-edge next-generation formats like as AVIF and WebP provide notable improvements in file size reduction without significantly sacrificing image quality. For example, it is possible to compress a 319 KB PNG image to as little as 38 KB in WebP format or, even more impressively, as little as 10 KB in AVIF format. These file size reductions are accomplished with little discernible loss of quality to the human eye, indicating that these formats have the potential to improve website loading times without sacrificing visual quality.

It’s crucial to remember that not every browser can support AVIF and WebP images. Make sure these formats work with the majority of browsers your audience uses before incorporating them into your website. This will assist you in evaluating whether these next-generation image formats meet the needs of your audience and the specifications of your website.

Caching

Memory, disk, service workers cache

Once a page loads, loading times can be greatly decreased by making use of Service Workers, memory caching, and disk cache. This is due to the fact that various caching algorithms need to load files just once in order to cache them. RAM-based memory cache provides quick access, but it is erratic. Disk cache, on the other hand, offers persistence despite being slower. By serving as programmable network proxies, service workers allow for advanced memory and disk caching techniques.

Unless there’s a specific need to control memory and disk caches programmatically, memory and disk caches are typically managed automatically by operating systems or browsers. To improve control over caching and network interactions, developers can create bespoke Service Workers in addition to Flutter, even if Flutter controls Service Workers to some extent.

Wasm

Both the compiled native code and Wasm files (such as CanvasKit and shortly dart2wasm output) are cached by browsers. As a result, unlike JavaScript, which needs to undergo reparsing, recompilation, and reJIT (Just-In-Time) processing, cached Wasm modules load just as quickly as native binaries.

Even though the Wasm build option for Flutter isn’t quite stable yet, you’ll profit when dart2wasm stabilizes if you use contemporary JS-interop methods. For example, use package:web and dart:js_interop instead of legacy libraries like dart:html and dart:js. Additionally, think about seeing if Wasm can be used with the other products you are now using.

Preloading

HTML , HTTP response headers

Website loading times can be greatly increased by preloading resources including fonts, pictures, and JavaScript files. You can tell the browser to download these resources ahead of time so they can be used for rendering by preloading them inside the HTML tag or by using HTTP response headers. Delays are removed, and a more seamless user experience is guaranteed. Add the element to the section and set the rel attribute to preload in order to preload assets. Only preload assets that will be used on your app’s first screen and as efficiently as possible; otherwise, browsers will view the preloading as a bandwidth waster.

HTML tag

				
					<head>
  <link rel="preload" href="assets/logo.webp" as="image" type="image/webp" />
</head>
<body>
  <picture>
    <source src="assets/logo.webp" type="image/webp" />
  </picture>
</body>
				
			

HTTP response headers for Firebase hosting

A firebase is the code block that follows.a key/value pair in a JSON sample that shows how to add HTTP headers for asset preloading.

				
					"headers": [
  {
    "key": "Link",
    "value": "<assets/logo.webp>; rel=preload; as=image"
  }
]
				
			

Landing page

With Flutter, you can use plain HTML and CSS to create fully interactive landing pages for your app. Flutter.js preloads your Flutter app as users interact with your landing page, guaranteeing quick launches when the user navigates to the Flutter app. This is particularly helpful for programs that need logging in and games with a Play button.

Loading/splash screen

Although we’ve concentrated on technological improvements to speed up app loading, user perception of loading speed is more important. Making your app feel speedy should be your main objective.

Splash and loading screens work wonders to improve this impression. They reassure consumers that the software is opening quickly by offering visual activity. On the other hand, a blank screen encourages doubt, which might result in annoyance and frequent page refreshes.

Use basic CSS/HTML to incorporate your splash screen straight into your index.html file for the quickest response. This reduces the possibility of any delays.

For an example, check out the Flutter Gallery implementation.

Conclusion

We’ve looked at techniques to improve your Flutter web app’s rendering and initial loading times in this document. You can use a variety of tactics, but keep in mind that every solution has trade-offs. Select the improvements that best meet your unique requirements as well as the demands of your users. You can make your Flutter web apps more responsive and seamless to use by combining these techniques.

Table of Contents

Recent Comments
    October 2024
    M T W T F S S
     123456
    78910111213
    14151617181920
    21222324252627
    28293031  
    Tags:
    androidiOSmobilemobile app development
    5 likes
    Leave a Comment
    Share:
    Social