Dart 如何判断NetworkImage何时完成加载?

Dart 如何判断NetworkImage何时完成加载?,dart,flutter,Dart,Flutter,我有一个箱子,我想知道什么时候装完。我该怎么做?您可以解析以获得ImageStream并将侦听器添加到ImageStream import 'package:flutter/material.dart'; void main() { runApp(new MyApp()); } class MyApp extends StatefulWidget { State createState() => new MyAppState(); } class MyAppState ext

我有一个箱子,我想知道什么时候装完。我该怎么做?

您可以
解析
以获得
ImageStream
将侦听器添加到
ImageStream

import 'package:flutter/material.dart';

void main() {
  runApp(new MyApp());
}

class MyApp extends StatefulWidget {
  State createState() => new MyAppState();
}

class MyAppState extends State<MyApp> {
  Image _image = new Image.network(
    'https://flutter.io/images/flutter-mark-square-100.png',
  );
  bool _loading = true;

  @override
  void initState() {
    _image.image.resolve(new ImageConfiguration()).addListener((_, __) {
      if (mounted) {
        setState(() {
          _loading = false;
        });
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      home: new Scaffold(
        body: new Center(
          child: _loading ? new Text('Loading...') : _image,
        ),
      ),
    );
  }
}
导入“包装:颤振/材料.省道”;
void main(){
runApp(新的MyApp());
}
类MyApp扩展了StatefulWidget{
State createState()=>新建MyAppState();
}
类MyAppState扩展了状态{
Image\u Image=new Image.network(
'https://flutter.io/images/flutter-mark-square-100.png',
);
bool_加载=真;
@凌驾
void initState(){
_image.image.resolve(新的ImageConfiguration()).addListener((u,uu){
如果(已安装){
设置状态(){
_加载=假;
});
}
});
}
@凌驾
小部件构建(构建上下文){
返回新材料PP(
家:新脚手架(
正文:新中心(
子项:_加载?新文本('加载…'):_图像,
),
),
);
}
}

我在颤振官方演示中找到了这种方法,希望能对您有所帮助

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

void _imageLoad() async {

    String imageName = "";

    Image downloadImage = new Image.network(imageName);

    final ImageStream stream = downloadImage.image.resolve(ImageConfiguration.empty);
    final Completer<void> completer = Completer<void>();
    stream.addListener((ImageInfo info, bool syncCall) => completer.complete());
    await completer.future;
    if (mounted) {
      //do sth
    }
}
导入'dart:async';
进口“包装:颤振/材料.省道”;
void\u imageLoad()异步{
字符串imageName=“”;
Image downloadImage=newimage.network(imageName);
final ImageStream=downloadImage.image.resolve(ImageConfiguration.empty);
最终完成者完成者=完成者();
stream.addListener((ImageInfo,bool syncCall)=>completer.complete());
等待完成者。未来;
如果(已安装){
//做某事
}
}

您可以使用ImageStreamListener来完成。ImageStreamListener的第一个参数是ImageListener回调,当图像完全加载时调用该回调

 var _image = NetworkImage("URL");

 _image.resolve(ImageConfiguration()).addListener(
    ImageStreamListener(
      (info, call) {
        print('Networkimage is fully loaded and saved');
        // do something
      },
    ),
  );

感谢您的评论,这有助于解决如何知道图像是否已加载的问题,希望能有所帮助

我使用StatefulWidget,需要根据您的粘贴屏幕进行编辑

情况:

-i have an url that i enter 
 -if url is correct affich the image if not affich an icon
 -if empty affich a Text()
 -precacheImage check if the url is correct if not give an error 
 -and change _loadingimage(bool) to false to affich the icon eror
 -i use a NetworkImage to check with precacheImage and before 
 -affich use a Image.network 

bool _loadingimage;
ImageProvider _image;
Image _imagescreen;

@override
  void initState() {
    _loadingimage = true;
    _imageUrlfocusNode.addListener(_updateImageUrl);
    super.initState();
  }

   @override
  void dispose() {
    _imageUrlfocusNode.removeListener(_updateImageUrl);
    _quantityfocusNode.dispose();
    _imageUrlConroller.dispose();
    _imageUrlfocusNode.dispose();
    super.dispose();
  }

  void _updateImageUrl() {
    setState(() {
      _image = NetworkImage(_imageUrlConroller.text);
    });
    if (!_imageUrlfocusNode.hasFocus) {
      if (_imageUrlConroller.text.isNotEmpty) {
        setState(() {
          loadimage();
        });
      }
    }
  }

  void loadimage() {
    _loadingimage = true;
    precacheImage(_image, context, onError: (e, stackTrace) {
      // log.fine('Image ${widget.url} failed to load with error $e.');
      print('error $e');
      setState(() {
        _loadingimage = false;
        print(_loadingimage);
      });
    });
    if (_loadingimage == true) {
      _imagescreen = Image.network(
        _imageUrlConroller.text,
        fit: BoxFit.fill,
      );
    }
  }



  Container(
                              width: 100,
                              height: 100,
                              margin: EdgeInsets.only(top: 13, right: 11),
                              decoration: BoxDecoration(
                                border: Border.all(
                                  width: 1,
                                  color: Colors.grey,
                                ),
                              ),
                              child:_imageUrlConroller.text.isEmpty
                                      ? Text('enter an url')
                                      : !_loadingimage
                                          ? Container(
                                              child: Icon(Icons.add_a_photo),
                                            )
                                          : Container(
                                              child: _imagescreen,
                                            ),
                            ),

您可以使用
loadingBuilder
,它为
Image.Network

以下示例使用
loadingBuilder
在图像通过网络加载时显示
CircularProgressIndicator

   Image.network(
      'https://example.com/image.jpg',
      loadingBuilder: (BuildContext context, Widget child,
          ImageChunkEvent loadingProgress) {
        if (loadingProgress == null) return child;
        return Center(
          child: CircularProgressIndicator(
            value: loadingProgress.expectedTotalBytes != null
                ? loadingProgress.cumulativeBytesLoaded /
                loadingProgress.expectedTotalBytes
                : null,
          ),
        );
      },
    )

2021年更新

_image.image.resolve(ImageConfiguration())
     .addListener(ImageStreamListener((ImageInfo info, bool syncCall) {

// DO SOMETHING HERE

completer.complete();

});

是否需要以某种方式关闭此imageStream?现在必须将侦听器编写为:_image.image.resolve(ImageConfiguration()).addListener(ImageStreamListener((ImageInfo信息,bool syncCall)=>completer.complete());也适用于
Image.file
Image.memory