dartflutter

How do I determine the width and height of an image in Flutter?


Assume I have declared my image in my pubspec.yaml like this:

  assets:
    - assets/kitten.jpg

And my Flutter code is this:

void main() {
  runApp(
    new Center(
      child: new Image.asset('assets/kitten.jpg'),
    ),
  );
}

Now that I have a new Image.asset(), how do I determine the width and height of that image? For example, I just want to print out the image's width and height.

(It looks like dart:ui's Image class has width and height, but not sure how to go from widget's Image to dart:ui's Image.)

Thanks!


Solution

  • UPDATED SOLUTION:

    With the new version of flutter old solution is obsolete. Now the addListener needs an ImageStreamListener.

    import 'dart:ui' as ui;
    
    Widget build(BuildContext context) {
        Image image = Image.network('https://i.sstatic.net/lkd0a.png');
        Completer<ui.Image> completer = Completer<ui.Image>();
        image.image
          .resolve(ImageConfiguration())
          .addListener(
              ImageStreamListener(
                  (ImageInfo info, bool _) => completer.complete(info.image)));
        ...
        ...
    

    ORIGINAL VERSION:

    If you already have an Image widget, you can read the ImageStream out of it by calling resolve on its ImageProvider.

    screenshot

    import 'dart:ui' as ui;
    import 'dart:async';
    import 'package:flutter/material.dart';
    import 'package:flutter/services.dart';
    
    void main() {
      runApp(new MaterialApp(
        home: new MyHomePage(),
      ));
    }
    
    class MyHomePage extends StatelessWidget {
    
      Widget build(BuildContext context) {
        Image image = new Image.network('https://i.sstatic.net/lkd0a.png');
        Completer<ui.Image> completer = new Completer<ui.Image>();
        image.image
          .resolve(new ImageConfiguration())
          .addListener((ImageInfo info, bool _) => completer.complete(info.image));
        return new Scaffold(
          appBar: new AppBar(
            title: new Text("Image Dimensions Example"),
          ),
          body: new ListView(
            children: [
              new FutureBuilder<ui.Image>(
                future: completer.future,
                builder: (BuildContext context, AsyncSnapshot<ui.Image> snapshot) {
                  if (snapshot.hasData) {
                    return new Text(
                      '${snapshot.data.width}x${snapshot.data.height}',
                      style: Theme.of(context).textTheme.display3,
                    );
                  } else {
                    return new Text('Loading...');
                  }
                },
              ),
              image,
            ],
          ),
        );
      }
    }