Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I tell when a NetworkImage has finished loading?

Tags:

flutter

dart

I have a NetworkImage and I'd like to know when it's finished loading. How do I do that?

like image 714
Seth Ladd Avatar asked Sep 20 '17 15:09

Seth Ladd


3 Answers

You can resolve to get an ImageStream and addListener to the 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,
        ),
      ),
    );
  }
}
like image 183
Collin Jackson Avatar answered Oct 23 '22 13:10

Collin Jackson


You can do it, with an ImageStreamListener. The first Parameter of the ImageStreamListener is an ImageListener Callback which is called, when the image is fully loaded.

 var _image = NetworkImage("URL");

 _image.resolve(ImageConfiguration()).addListener(
    ImageStreamListener(
      (info, call) {
        print('Networkimage is fully loaded and saved');
        // do something
      },
    ),
  );
like image 41
timo Avatar answered Oct 23 '22 13:10

timo


I find this method in flutter official demo,wish help you.

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
    }
}
like image 5
qingtiandashen Avatar answered Oct 23 '22 14:10

qingtiandashen