How to work with browser from Flutter Web

It’s a bit unclear what to do if something web-specific is required in a Flutter Web app. Let’s look at available options.

For example, let’s try to open a link in a new tab.

Try to find Flutter package

We can find the required package:

https://pub.dev/packages/url_launcher

It’s better to use a package if it’s already compatible with Flutter Web.

Note: as Flutter Web is still new not all packages support it.

Code:

import 'package:url_launcher/url_launcher.dart';
_launchUrl() async {
  const url = 'https://flutter.dev';
  if (await canLaunch(url)) {
    await launch(url);
  } else {
    throw 'Could not launch $url';
  }
}

Check dart:html if you want to work with DOM

Good initial reading about this library:

https://dart.dev/tutorials/web/low-level-html/connect-dart-html

It’s more low level than ready to use package. Also, it requires a web browser.

Code:

import 'dart:html' as html;
_launchUrl() async {
  const url = 'https://flutter.dev';
  html.window.open(url, '_blank');
}

Use dart:js / package:js if you want to run Javascript functions from Flutter

Dart:js code:

import 'dart:js' as js;
_launchUrl() async {
  const url = 'https://flutter.dev';
  js.context.callMethod('launchUrl', [url, '_blank']);
}

launchUrl should exist as a Javascript function on the page. For example, it can be added to web/index.html like this:

<script type="application/javascript">
function launchUrl(url, target) { 
    window.open(url, target); 
} 
</script>

Flutter team says that it’s better to use package:js instead of dart:js:

https://pub.dev/packages/js

In this case, the Javascript part is the same but the Flutter part is different:

@JS()
library launchUrl;

import 'package:js/js.dart';

@JS('launchUrl')
external String launchUrl(String url, String target);
_launchUrl() async {
  const url = 'https://flutter.dev';
  launchUrl(url, '_blank');
}

So, it’s more code but it’s better organized.

How to check if we are on the web or not?

Just code:

import 'package:flutter/foundation.dart';
if (kIsWeb) {
  print("It's web");
}