Flutter Web is growing in popularity and it’s becoming more and more mature as the time passes. We’re not there with perfection, there are still some issues but hopefully they’re going to be solved soon!

If you’ve had the chance to fiddle around with a Flutter project that targets you might have found yourself trapped in this situation:

I need this feature, I could use this plugin that already does that, but it doesn’t support Web.

Then you answer yourself something like this:

Well I’ll wrap it into a factory, if kIsWeb is true then I’m on Web and return the Web-compatible instance!

Well, yes. And no. Let’s break this down.

Since I first encountered the problem when adding Auth0 authentication in my app, I’ll take this as our use case.

There is a plugin that allows to use Auth0 on mobile, but it doesn’t support Web. I’d tell you why it’s not that easy to develop a Web part for this, but I’m currently working on a dedicated article which explores the non-triviality of implementing auth0 on Flutter Web and how I’ve found a way to do it. I’ll update this article with the link when it’ll be ready, but for now, since those reasons are not in the scope of this article, let’s talk generally.

So the plugin provides an Auth0 class which allows us to perform the tasks.

We decide to wrap those tasks in another class in order to leverage the factory (and to encapsulate the plugin for architectural reasons, of course).

Our abstract class will be:

abstract class AuthManager {
  static AuthManager _instance;

  static AuthManager get instance {
    if (_instance == null) {
      if (kIsWeb) {
        _instance = Auth0ManagerForWeb();
      } else {
        _instance = Auth0Manager();
      }
    }
    return _instance;
  }
  
  Future<User> login([Map<String, String> authResponse]);
  Future<User> userFromTokens(String idToken, String accessToken);
  Future<void> logout();
}

I didn’t use a factory but a bunch of if just to avoid creating a real factory that we’d throw away afterwards (trust me on it).

#flutter #mobile-apps #web-development

Conditional Imports Across Flutter and Web
10.75 GEEK