flutterflutter-imageflutter-downloader

Download a Widget as PNG in flutter WEB


I'm trying to download a widget as an image via flutter. Everything works so far, but the file is displayed with the error: network error.

WidgetsToImage converts the widget that follows into an image. Using the flutter html libary I try to download the image via url command.

Here is my code in Flutter. The widget Text() should be converted to an image and then downloaded.

import 'dart:typed_data';

import 'package:flutter/material.dart';
import 'package:widgets_to_image/widgets_to_image.dart';
import 'dart:html' as html;

void main() {
  runApp(const MyApp());
}

Color contrastColor = Colors.black;
Color mainColor = Colors.white;

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  WidgetsToImageController controller = WidgetsToImageController();
  Uint8List? bytes;

  Future<void> saveImg() async {
    final bytes = await controller.capture();
    final anchor =
        html.AnchorElement(href: 'data:application/octet-stream;base64,$bytes')
          ..download = "image.png"
          ..target = 'blank';

    html.document.body!.append(anchor);
    anchor.click();
    anchor.remove();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Column(
        children: [
          Center(
            child: ElevatedButton(
              child: Text("TEST"),
              onPressed: () => saveImg(),
            ),
          ),
          WidgetsToImage(
            child: Text("HALLO WELT"),
            controller: controller,
          )
        ],
      ),
    );
  }
}

The error


Solution

  • It was an easy fix:

    Future<void> _downloadImage() async {
        final bytes = await controller.capture();
        await WebImageDownloader.downloadImageFromUInt8List(uInt8List: bytes!);
      }