Either drawImage or paintImage doesn't work properly in Flutter

4,856

There are two classes called Image in flutter, in different packages.

There's the Widget, which behaves like a widget and can be instantiated from an asset, from memory or from the network through its named constructors.

There's also the ui package Image which is used when painting at a lower level, for example in a CustomPainter. Since this version is in the ui package it's normally imported with the ui prefix like this:

import 'dart:ui' as ui;

Don't import material as ui! That will lead to a lot of confusion.

To make a widget, use the Image.asset constructor, passing the asset name.

To make a ui.Image from an asset use this snippet:

  Future<ui.Image> load(String asset) async {
    ByteData data = await rootBundle.load(asset);
    ui.Codec codec = await ui.instantiateImageCodec(data.buffer.asUint8List());
    ui.FrameInfo fi = await codec.getNextFrame();
    return fi.image;
  }
Share:
4,856
BenSabo
Author by

BenSabo

Updated on December 06, 2022

Comments

  • BenSabo
    BenSabo over 1 year

    I basically want to show an image that I have in the assets folder onto the canvas.

        import 'package:flutter/material.dart' as ui;
    
        ...
    
        ui.Image img = ui.Image.asset("images/some_image.png");
        ui.paintImage(canvas: canvas, image: img);
    

    And have got the following error message when I tried to assign img to paintImage's image.

    The argument type 'Image (C:\ABC\flutter\packages\flutter\lib\src\widgets\image.dart)' can't be assigned to the parameter type 'Image (C:\ABC\flutter\bin\cache\pkg\sky_engine\lib\ui\painting.dart)'.

    I don't really know what could go wrong, I have seen other codes that had a similar approach with ui.Image.

    Please advise.

  • BenSabo
    BenSabo over 5 years
    Ah, i see. Thank you
  • Damandroid
    Damandroid over 4 years
    I came upon this answer now and having a very similar problem. My image is a base64Encoded string so I am trying to do the following: void paint(Canvas canvas, Size size) async { canvas.drawImage(await load(image), Offset(0.0, 0.0), Paint()); ... Future<ui.Image> load(String image) async { Uint8List bytes = base64Decode(image); ui.Codec codec = await ui.instantiateImageCodec(bytes); // ui.Codec codec = await ui.instantiateImageCodec(data.buffer.asUint8List()); ui.FrameInfo fi = await codec.getNextFrame(); return fi.image; *and getting Unable to load error
  • Richard Heap
    Richard Heap over 4 years
    Best to ask a new question.
  • princeoo7
    princeoo7 over 3 years
    @Damandroid did you got the solution for your query above ?
  • Damandroid
    Damandroid over 3 years
    No @princeoo7. It went on a back burner for now.