Search code examples
imageflutterpdfsharedpreferences

Load image from sharedPreferences to pdf in Flutter


I'm need to load a image from sharedPreferences to a pdf document. The image loads normally when in normal use, but i don't know how to make it load in the pdf. When I try to load it like a normal image I get "Unhandled Exception: type 'Image' is not a subtype of type 'PdfImage'"

This is how I use it normally.

import 'package:flutter/material.dart';
import 'package:flutter_settings_screens/flutter_settings_screens.dart';
import 'package:image_picker/image_picker.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:MyApp/SharedPrefUtility.dart';

Future<void> initSettings() async {
  await Settings.init(
    cacheProvider: SharePreferenceCache(),
  );
}

class ProfilePage extends StatefulWidget {
  @override
  _ProfilePageState createState() => _ProfilePageState();
}

class _ProfilePageState extends State<ProfilePage> {
  Image logo;

  pickImage(ImageSource source) async {
    final _image = await ImagePicker.pickImage(source: ImageSource.gallery);

    if (_image != null) {
      setState(() {
        logo = Image.file(_image);
      });
      ImageSharedPrefs.saveImageToPrefs(
          ImageSharedPrefs.base64String(_image.readAsBytesSync()));
    } else {
      print('Error picking image!');
    }
  }

  loadImageFromPrefs() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    final imageKeyValue = prefs.getString(IMAGE_KEY);
    if (imageKeyValue != null) {
      final imageString = await ImageSharedPrefs.loadImageFromPrefs();
      setState(() {
        logo = ImageSharedPrefs.imageFrom64BaseString(imageString);
      });
    }
  }

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.red,
        title: Text('Profile Settings'),
      ),
      body: Center(
        child: ListView(
          children: [
            Column(
              crossAxisAlignment: CrossAxisAlignment.center,
              mainAxisAlignment: MainAxisAlignment.start,
              children: <Widget>[
                ClipRect(
                  child: Container(
                    width: 300,
                    height: 300,
                    child: logo == null ? Text('No image selected.') : logo,
                  ),
                ),
                RaisedButton(
                  onPressed: () {
                    pickImage(ImageSource.gallery);
                  },
                  child: Text('Pick Company Logo'),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }
}

With SharedPrefUtility.dart

import 'dart:convert';
import 'dart:typed_data';
import 'package:flutter/widgets.dart';
import 'package:shared_preferences/shared_preferences.dart';

const IMAGE_KEY = 'IMAGE_KEY';

class ImageSharedPrefs {
  static Future<bool> saveImageToPrefs(String value) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();

    return await prefs.setString(IMAGE_KEY, value);
  }


  static Future<String> loadImageFromPrefs() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    return prefs.getString(IMAGE_KEY);
  }

  static String base64String(Uint8List data) {
    return base64Encode(data);
  }

  static imageFrom64BaseString(String base64String) {
    return Image.memory(
      base64Decode(base64String),
      fit: BoxFit.contain,
    );
  }
}

Any Suggestions would be great.


Solution

  • davey06 gave the answer on gitHub

       final imageString = await ImageSharedPrefs.loadImageFromPrefs(); 
    // Create a PDF document.
    final document = pw.Document();
    
    // Add page to the PDF
    document.addPage(pw.Page(build: (context) {
      return pw.Center(
        child: pw.Image(
          PdfImage.file(document.document, bytes: base64Decode(imageString)),
        ),
      );
    }));
    
    // Return the PDF file content
    return document.save();
    

    https://github.com/DavBfr/dart_pdf/issues/477