在Flutter中显示来自Internet的图像

时间:2019-07-17 00:43:12

标签: flutter dart

我正在尝试从可能符合或不符合某些条件的API加载图像。如果这些条件成功,我想在屏幕上显示图像。看来我可以使用NetworkImage来加载它并检查属性,如果这些属性匹配,我会在列表中添加一个图像。

但是,我不太清楚如何将NetworkImageImage.fromMemory一起使用(我猜是这样)

这段代码似乎可以帮助我解决大部分问题(但是在我调用load之后添加一个侦听器似乎很可疑)。

  Future getImage() async {
    var url = 'https://myapi.com/a37ni1.jpg';
    var image = new NetworkImage(url);
    var config = await image.obtainKey(new ImageConfiguration());
    var load = image.load(config);

    var listener = new ImageStreamListener((ImageInfo info, isSync) async {
      print(info.image.width);
      print(info.image.height);

      if (info.image.width == 80 && info.image.height == 160) {
        //skip
      } else {

        //Convert the NetworkImage to something I can use in an Image widget
      }
    });

    load.addListener(listener);
  }

有什么主意我可能会在这里错过吗?

1 个答案:

答案 0 :(得分:1)

这是一个示例,但我使用了另一个网址而不是您的网址

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

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        appBar: AppBar(title: Text("Test")),
        body: Container(
          alignment: Alignment.center,
          child: FutureBuilder<Widget>(
            future: getImage(),
            builder: (context, snapshot) {
              if (snapshot.hasData) {
                return snapshot.data;
              } else {
                return Text('LOADING...');
              }
            },
          ),
        ),
      ),
    );
  }

  Future<Widget> getImage() async {
    final Completer<Widget> completer = Completer();

    final url = 'https://picsum.photos/200/300';
    final image = NetworkImage(url);
    final config = await image.obtainKey(const ImageConfiguration());
    final load = image.load(config);

    final listener = new ImageStreamListener((ImageInfo info, isSync) async {
      print(info.image.width);
      print(info.image.height);

      if (info.image.width == 80 && info.image.height == 160) {
        completer.complete(Container(child: Text('AZAZA')));
      } else {
        completer.complete(Container(child: Image(image: image)));
      }
    });

    load.addListener(listener);
    return completer.future;
  }
}