Flutter app with a button for taking a screenshot in flutter displayed only on web platform

I’ve a flutter 3.0 widget with a button taking a screenshot that is displayed only on web platform. Here is my code

import 'dart:convert';
import 'dart:html' as html;

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

import 'package:screenshot/screenshot.dart';

...
@override
  Widget build(BuildContext context) {
        ...
        if (kIsWeb)
            SizedBox(
              width: 200,
              height: 55.0,
              child: ElevatedButton(
                child: const Padding(
                  padding: EdgeInsets.all(10.0),
                  child: Text(
                    'DOWNLOAD'
                  ),
                ),
                onPressed: () async {
                  await screenshotController.capture(delay: const Duration(milliseconds: 10)).then((aaa) async {
                    final _base64 = base64Encode(aaa!);
                      final anchor =
                          html.AnchorElement(href: 'data:application/octet-stream;base64,$_base64')
                            ..download = "image.png"
                            ..target="blank";
                    
                      anchor.click();
                      anchor.remove();
                  });
                }
              ),
            ),

This code is compiled on web platform. But on android i get the error

lib/main.dart:91:32: Error: Method not found: 'AnchorElement'.
                          html.AnchorElement(href: 'data:application/octet-stream;base64,$_base64')

  • It looks like your block of code is meant to be executed on the web platform only with a check placed as kIsWeb. Not sure if there is separate logic for other platforms.

    – 

Leave a Comment