Image is null with Uint8List - Flutter

5.1k Views Asked by At

I am trying to encode an image to Uint8List but it gives me a null

  List<int> bytes;
  I.Image _img;

  @override
  void initState() {
    super.initState();
    WidgetsFlutterBinding.ensureInitialized();
    String file = 'lib/graphics/logo.png';
    readFileAsync(file);
  }

  Future<dynamic> readFileAsync(String filePath) async {
    var imageData = await rootBundle.load('lib/graphics/logo.png');
    bytes = Uint8List.view(imageData.buffer);
    _img = I.decodeImage(bytes);
  }

and calling it from the widget tree

Container(
  child: Image.memory(_img.getBytes()),
),

Error

I/flutter (26125): ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
I/flutter (26125): The following NoSuchMethodError was thrown building LayoutBuilder:
I/flutter (26125): The method 'getBytes' was called on null.
I/flutter (26125): Receiver: null
I/flutter (26125): Tried calling: getBytes()
1

There are 1 best solutions below

1
On BEST ANSWER

You get a null because the load method is a Future and you don't wait for it on your build method.

You have to check if _img is null and display another widget like a Text or CircularProgressIndicator if it is :

Container(
  child: _img ? Image.memory(_img.getBytes()) : Text('loading...'),
), 

After, you need to call the setState() method to rebuild your widget in your readFileAsync method :

setState() {
  _img = I.decodeImage(bytes);
}