如何从扑扑的NetworkImage获取大小

我创建了一个应该返回网络图像大小的类,但是它不起作用,我不知道为什么。 所以我想要的工作方式是将图像URL传递给类,然后在类构造函数上调用_ImageSize函数,并设置类的height和width属性

import 'dart:async';
import 'dart:ui' as ui;
import 'package:flutter/material.dart';

class ImageSize {
  double height;
  double width;
  final String imgName;

  ImageSize(this.imgName) {
    _imageSize();
  }

  void _imageSize() {
    Future<ui.Image> _getImageInfo() {
      Completer<ui.Image> completer = Completer<ui.Image>();
      NetworkImage(this.imgName).resolve(ImageConfiguration()).addListener(
        ImageStreamListener(
          (ImageInfo info, bool _) => completer.complete(info.image),
        ),
      );
      return completer.future;
    }

    _getImageInfo().then((size) {
      print(size);
      height = size.height.toDouble();
      width = size.width.toDouble();
    }).catchError((e) {
      print(e);
    });
  }
}

main() async {
  double height = ImageSize(
      'https://images.pexels.com/photos/20787/pexels-photo.jpg?auto=compress&cs=tinysrgb&dpr=1&w=500'
  ).height;
  print(height);
}
评论