Flutter-如何制作可以解析Future ImageProvider的FutureBuilder

时间:2019-10-13 12:32:55

标签: flutter

我想消除用于等待的样板代码,然后用最终图像替换ImageProvider占位符。

以下内容适用于图像小部件。

class FutureImage extends StatelessWidget {
  final Future<Image> futureImage;
  final Image placeholder;

  const FutureImage({Key key, this.futureImage, this.placeholder})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    return FutureBuilder(
      future: futureImage,
      builder: (BuildContext context, AsyncSnapshot<Image> image) {
        if (image.hasData) {
          return image.data; 
        } else {
          return placeholder; 
        }
      },
    );
  }
}

但是我需要一个ImageProvider(因为它可以在Image不能使用的地方使用)

以下操作无效,因为ImageProvider不是小部件:

class FutureImageProvider extends StatelessWidget {
  final Future<ImageProvider> futureImageProvider;
  final ImageProvider placeholder;

  const FutureImageProvider(
      {Key key, this.futureImageProvider, this.placeholder})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    return FutureBuilder(
      future: futureImageProvider,
      builder: (BuildContext context, AsyncSnapshot<ImageProvider> image) {
        if (image.hasData) {
          return image.data; 
        } else {
          return placeholder; 
        }
      },
    );
  }
}

0 个答案:

没有答案