I'm building a Flutter app that I am trying to make work on the web. Part of it contains some web specific code:
import 'dart:html' as html;
import 'package:flutter/foundation.dart';
class DownloadViewModel extends ChangeNotifier {
static const String url = 'https://example.com/api/v1/app/myapp_1.0.0.apk';
void onAndroidDownloadPressed() {
html.window.open(url, 'AndroidApp');
}
}
However the dart:html
import gives the following error:
Avoid using web-only libraries outside Flutter web plugin packages
The longer version of the warning looks like this:
Avoid using web libraries,
dart:html
,dart:js
anddart:js_util
in Flutter packages that are not web plugins. These libraries are not supported outside a web context; functionality that depends on them will fail at runtime in Flutter mobile, and their use is generally discouraged in Flutter web.Web library access is allowed in:
plugin packages that declare web as a supported context
otherwise, imports of
dart:html
,dart:js
anddart:js_util
are disallowed.
And it's not just a warning. This actually prevents building an Android or iOS app (even though this method isn't accessible from non-Web Flutter apps).
The only solution I've figured out is to comment out the import when I am building for Android and iOS and then uncomment it when I am building for the web. Is there a better solution?