0

I'm trying to build an in app gallery function where I can screenshot certain widgets in the app and then display it inside the app's internal gallery screen. Currently, I am using the Flutter screenshot package and then I save the screenshot to the Application document directory path. But how do I retrieve the images back and display them later on the app again?

mango
  • 1

1 Answers1

1

Here's how I've done it before using the path_provider package. (this is only for one image, but you can adapt the code to retrieve multiple images).

Create an uninitialized variable:

Image? image;

then, in the initState:

void initState() {
    _loadImage();
    super.initState();
  }

Here is the _loadImage()

  Future<void> _loadImage() async {
    final path = await imagePath;
    final _doesTheImageExist = File('${path}/qr.png').existsSync();
    print(_doesTheImageExist);
    if (_doesTheImageExist == true) {
      setState(() {
        image = Image.file(File("${path}/qr.png"));
      });
    } else {
      print('no');
      setState(() {
        image = null;
      });
    }
  }

Create a getter to get the image path imagePath:

  Future<String> get imagePath async {
    final directory = (await getApplicationDocumentsDirectory()).path;
    return '$directory/qr.png';
  }

then, create a function to save the image to the device:

Future<void> _captureAndSaveQRCode() async {
    final imageDirectory = await imagePath;

    await _screenshotController.captureAndSave(imageDirectory,
        fileName: 'qr.png');
    await _loadImage();
    // setState(() {});
  }

Here is the complete runnable example:

import 'dart:io';
import 'package:flutter/material.dart';
import 'package:path_provider/path_provider.dart';
import 'package:qr_flutter/qr_flutter.dart';
import 'package:screenshot/screenshot.dart';

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const Scaffold(
        body: QrCode(),
      ),
    );
  }
}

class QrCode extends StatefulWidget {
  const QrCode({Key? key}) : super(key: key);

  @override
  State<QrCode> createState() => _QrCodeState();
}

class _QrCodeState extends State<QrCode> {
  final _screenshotController = ScreenshotController();

  Image? image;
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: image != null
          ? Center(
          child: Padding(
            padding: const EdgeInsets.only(
              top: 100.0,
            ),
            child: Column(
              children: [
                image!,
              ],
            ),
          ))
          : Center(
        child: Column(
          children: [
            TextButton(
                onPressed: _captureAndSaveQRCode,
                child: Text("Save QrCode")),
            Screenshot(
                controller: _screenshotController,
                child: _buildQRImage('data'))
          ],
        ),
      ),
    );
  }

  Widget _buildQRImage(String data) {
    return QrImage(
      data: data,
      size: 250.0,
      version: QrVersions.auto,
      errorCorrectionLevel: QrErrorCorrectLevel.H,
      gapless: false,
      foregroundColor: Colors.black,
      backgroundColor: Colors.white,
    );
  }

  Future<String> get imagePath async {
    final directory = (await getApplicationDocumentsDirectory()).path;
    return '$directory/qr.png';
  }

  Future<void> _loadImage() async {
    final path = await imagePath;
    final _doesTheImageExist = File('${path}/qr.png').existsSync();
    print(_doesTheImageExist);
    if (_doesTheImageExist == true) {
      setState(() {
        image = Image.file(File("${path}/qr.png"));
      });
    } else {
      setState(() {
        image = null;
      });
    }
  }

  Future<void> _captureAndSaveQRCode() async {
    final imageDirectory = await imagePath;

    await _screenshotController.captureAndSave(imageDirectory,
        fileName: 'qr.png');
    await _loadImage();
  }



  @override
  void initState() {
    _loadImage();
    super.initState();
  }
}

MendelG
  • 14,885
  • 4
  • 25
  • 52