Flutterexperts

Empowering Vision with FlutterExperts' Expertise
Decoding Flutter Web challenges

Flutter is a popular framework for building modern, high-performance multi-platform applications. Developed by Google, Flutter is known for its fast, expressive, and flexible approach to building user interfaces. With Flutter, developers can create beautiful, interactive, and responsive web applications that work across a range of devices and browsers. However, like any new technology, Flutter for the web comes with its challenges. In this article, I’ll decode some of the challenges that developers may face when using Flutter for web development. I’ll also provide some tips and solutions for overcoming these challenges so that you can make the most out of this powerful framework. Whether you’re a seasoned web developer looking to learn more about Flutter, or a newcomer to the world of web development, this article will provide valuable insights into the challenges and rewards of using Flutter for the web.

If you’re looking for the best Flutter app development company for your mobile application then feel free to contact us at — support@flutterdevs.com.


Table of contents:

1. Customizing flutter web app initialization

2. Resource sharing restrictions?

3. Configure URL strategy

4. Plugins & Custom code in JS

5. Conclusion


Customizing flutter web app initialization

Flutter web uses _flutter.loader javascript API. This API can be used to display a loading indicator in CSS and prevent the app from loading based on a condition.

1. The initialization process is broken down into three steps.

  1. Fetches the main.dart.js script and initializes the service worker.
  2. Initializes Flutter’s web engine by downloading required resources such as assets, fonts, and CanvasKit.
  3. Prepares the DOM for your Flutter app and runs it.

https://gist.github.com/Aditsyal/45f003d0cc1ea4a908c95f96ffcac2a4

EntryPoint Initialization

The loadEntrypoint method has the following parameters which can be customized:

  1. entrypointUrl — This points to the URL of our Flutter app’s entrypoint which is defaulted to the main.dart.js file.
  2. serviceWorker —This sets the flutter_service_worker.js configuration file.
  3. serviceWorkerVersion — This takes the service worker version set by the build process in our index.html file.
  4. timeoutMillis — This points to the timeout value for the service worker loader which is defaulted to 4000ms.

Engine Initialization
By default, the Flutter engine is initialized using the initializeEngine() function but we can also call the autoStart() to start the app immediately with the default configuration.

https://gist.github.com/Aditsyal/b3524d851445bb06c1ff1d6c82cb1625

Using these you can customize your Flutter web app initialization to something like,

https://gist.github.com/Aditsyal/5322eee024a97e1c5803e4824a8b71a8

Resource sharing restrictions?

Have you ever come across a situation where your Flutter web app failed to load the images from the web or arbitrary sources on your desktop browsers? Let’s take a scenario, that your Flutter web app displays video thumbnails from youtube but somehow fails to do so and throws you an error, or the network images coming from a different domain throw an error. All these scenarios possibly hint at a single cause, Cross-Origin Resource Sharing (CORS). We’ll talk about CORS ahead but before that let’s understand how things work on the web at Flutter end and why CORS is the reason for your trouble. Flutter web uses two different renderers, each of which has different functionality, advantages, and limitations.

HTML renderer:
HTML renderer is one of the renderers responsible to render your web app on mobile browsers. It uses the HTML <img> element to render images which has certain advantages such as image optimization, memory management, and above all, it allows you to display images from arbitrary sources.

  1. Uses HTML, CSS, Canvas 2D, and SVG to render UI.
  2. Uses <img> and <picture> elements to render images.
  3. Display images from arbitrary sources.
  4. Advantages with browser caching.

But wait. If an HTML renderer can easily display images from arbitrary sources without any extra load then why are we facing issues? You’ll get to know that ahead.

HTML renderer despite having certain advantages does have a few limitations too but the one that matters is that it has limited access to image data i.e no image manipulation, no image pixels data hence limited use.

CanvasKit renderer:
It’s one of the renderers responsible for rendering your UI on desktop browsers and for that purpose it uses WebGL. It uses the HTML <canvas> element to render images and has far better advantages over HTML renderer when it comes to having control of image data which furthermore helps with image sizing, and reading more pixels data, and since it uses WebGL you have superlative control over the image.
To take the advantage of CanvasKit renderer and WebGL you will need to configure CORS for your data.

  1. Uses WebGL to render UI.
  2. Advantages with image sizing.
  3. Custom image algorithms.
  4. Access to image data for manipulation(if CORS configured).

Cross-Origin Resource Sharing i.e CORS
You would have heard this word a lot of times above and might be wondering what it is and why we need to deal with it. Well, it’s a security feature implemented by web browsers that prevent a web page from making requests to a different domain than the one that the page is served from. So basically, when you use <img> <picture> or <canvas> elements, the browser automatically blocks any data regarding pixels if the data is coming from a different domain. Therefore, you need to configure your CORS policy for the domain your images are coming from to be able to let canvaskit renderer works to its ability.

To curb this resource-sharing issue for your Flutter web app there are a few different solutions that you can implement,

Using HTML renderer

As we’ve read, HTML renderer though not the default renderer for Flutter for the web but does allow you to display images from arbitrary sources without any need for extra configurations. So, we can achieve that by forcing our web app to use an HTML renderer despite using the default CanvasKit renderer and we can do that by running the following command on the terminal,

flutter run -d chrome - web-renderer html

Using CORS configuration

Another way is to use your default renderer i.e CanvasKit renderer because using an HTML renderer has limitations that the default renderer solves but to be able to use images from arbitrary sources in CanvasKit renderer you will need to configure your CORS file for the domain you’re fetching the images from.
Below are the steps to configure your CORS file for the Firebase domain, in this scenario I’m assuming that the images are coming from the Firebase storage so we need to set up the CORS for the Firebase to do so follow the below steps,

  1. Download the Google Cloud sdk.
  2. In your Flutter project, create the cors.json file.
  3. In the terminal, navigate to the google-cloud-sdk/bin and run gcloud init.
  4. Authenticate yourself and choose your project.
  5. Run gsutil cors set cors.json gs://<your-bucket-name>.appspot.com where bucket-name is the name of the bucket where images are stored on Firebase storage.

This is how your cors.json file should look like, where I’ve set the origin as “*” which makes it accessible for all domains but you can replace it with your specific domain, for ex: “https://your-example-website.appspot.com”.

[
{
"origin": ["*"],
"method": ["GET"],
"maxAgeSeconds": 3600
}
]

Configure URL strategy

Flutter Web has two URL strategies for its apps

By default, Flutter uses the hash in its web app URLs but that can be a problem considering indexing and SEO-related queries on the web which can be an issue considering one of the critical aspects of the web. This is important because it allows the app to handle different types of URLs consistently and predictably.

For example, the URL strategy can be used to specify how the app should handle deep links, which are URLs that link directly to specific pages or sections within the app. This can make it easier for users to share links to specific parts of the app with other people, and it can also help improve the overall user experience of the app by making it more intuitive and navigable.

  1. Flutter web supports two ways to configure URLs.
    Hash(default): flutterexample.dev/#/path/to/screen.
    Path: flutterexample.dev/path/to/screen.
  2. To use PathUrlStrategy one needs to configure web server rewrites to index.html.
  3. You need to make sure that you include <base href=”/”> inside the <head> section of your web/index.html when using the path URL strategy.

https://gist.github.com/Aditsyal/e084e78dd4e77b335ec9fc93caa5fca2

The flutter_web_plugins library provides this method. The above method changes the URL strategy in your Flutter web app but you also need to handle various situations in the above scenario like handling it for the mobile app which involves a few conditional statements to make the implementation further simpler you can use the below plugin.

Plugin: url_strategy

  1. Use this plugin to simplify the implementation.
  2. It’s based on the previous solution provided by the flutter_web_plugins.
  3. You only need to call a single function.
  4. No need to use conditional imports.

https://gist.github.com/Aditsyal/abbc544db55a5f2d37d310ba635c1f1f

Plugins & Custom code in JS:

If you’ve integrated your existing Flutter code to be compatible with Flutter web then you might’ve come across a situation where the plugins that worked for you earlier might cause problems after the Flutter web integration. Well, this is highly possible as not all your previous plugins might support Flutter web,

Replacing your plugins:
One way is to replace your older plugins with the ones that are compatible with Flutter web, now this may or may not help you but you’ve to explore all the options available to avoid creating a plugin yourself that fits your requirements and also support Flutter web.

Custom native javascript code:
Now, having all plugins replaced or whatever could’ve been replaced you could still be in a situation where you want to get something done on the Flutter web app and there’s no plugin for that or maybe you know to achieve the task you could easily get it done using Javascript, yes you could write a javascript code and integrate it in your Flutter web app using the following steps,

1. Create a js file in the web folder of your project.

2. Write your custom method.

https://gist.github.com/Aditsyal/8f259742abce0fce69db3f49b4ff1ef6

3. Update the index.html file.

<script src="custom.js" defer></script>

4. Use the method in your dart code.

js.context.callMethod(
'customAlertMessage', ['Hey this is custom IS code! ']):

Conclusion:

In conclusion, Flutter for the web is a powerful framework for building modern, high-performance web applications. Despite its relative newcomer status, Flutter has quickly gained popularity among developers for its fast, expressive, and flexible approach to building user interfaces. However, like any new technology, Flutter for the web comes with its challenges. These challenges can range from the relative immaturity of the Flutter ecosystem to the lack of support for certain features and functionality. Despite these challenges, many developers are drawn to Flutter for the web because of its ability to create beautiful, interactive, and responsive web applications quickly and easily. By understanding the challenges and finding solutions to overcome them, developers can take full advantage of the benefits that Flutter for the web has to offer.

Thanks for reading this article.
If I got something wrong? Let me know in the comments. I would love to improve.


Feel free to connect with us:
And read more articles from FlutterDevs.com.

FlutterDevs team of Flutter developers to build high-quality and functionally-rich apps. Hire a flutter developer for your cross-platform Flutter mobile app project on an hourly or full-time basis as per your requirement! For any flutter-related queries, you can connect with us on Facebook, GitHub, Twitter, and LinkedIn.

We welcome feedback and hope that you share what you’re working on using #FlutterDevs. We truly enjoy seeing how you use Flutter to build beautiful, interactive web experiences.

Leave comment

Your email address will not be published. Required fields are marked with *.