Check image is loaded in Image.network widget in flutter

坚强是说给别人听的谎言 提交于 2021-01-20 16:39:46

问题


I am new to Flutter. I try to load network image using image.network widget. it's work fine but sometimes it's take time to load.I added tap listener to image.network during tap i need to check image is fully load or not based on the result I need to redirect page. how to check image is loaded or not ?

Code:

new Image.network('http://via.placeholder.com/350x150')

Any help will be appreciated, thank you in advance


回答1:


You may use the loadingBuilder which is inbuilt feature from flutter for Image.Network

I did it as below:

Image.network(imageURL,fit: BoxFit.cover,
  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,
      ),
    );
  },
),



回答2:


for this kind of issues it's good to use the cached_network_image so you can provide a placeholder when the image is loading and an error widget in case a resource fails to load

String url = "http://via.placeholder.com/350x150";
CachedNetworkImage(
       imageUrl: url,
       placeholder: (context,url) => CircularProgressIndicator(),
       errorWidget: (context,url,error) => new Icon(Icons.error),
     ),



回答3:


for ones who do not need to cache the image can use meet_network_image package,

The package basic usage :

                MeetNetworkImage(
                  imageUrl:
                      "https://random.dog/3f62f2c1-e0cb-4077-8cd9-1ca76bfe98d5.jpg",
                  loadingBuilder: (context) => Center(
                        child: CircularProgressIndicator(),
                      ),
                  errorBuilder: (context, e) => Center(
                        child: Text('Error appear!'),
                      ),
                )

In addition, you can do that by yourself with using a FutureBuilder,

We need to get data with http call that way, we need to import http before import you also need to add pubspec.yaml and run the command flutter packages get

import 'package:http/http.dart' as http;
  FutureBuilder(
    // Paste your image URL inside the htt.get method as a parameter
    future: http.get(
        "https://random.dog/3f62f2c1-e0cb-4077-8cd9-1ca76bfe98d5.jpg"),
    builder: (BuildContext context, AsyncSnapshot<http.Response> snapshot) {
      switch (snapshot.connectionState) {
        case ConnectionState.none:
          return Text('Press button to start.');
        case ConnectionState.active:
        case ConnectionState.waiting:
          return CircularProgressIndicator();
        case ConnectionState.done:
          if (snapshot.hasError)
            return Text('Error: ${snapshot.error}');
          // when we get the data from the http call, we give the bodyBytes to Image.memory for showing the image
          return Image.memory(snapshot.data.bodyBytes);
      }
      return null; // unreachable
    },
  );



回答4:


thank you for your comment thats help to resolve the situation that how to know if the image is loaded or not hope that help

I use a StatefulWidget need a editing depend on your AffichScreen

situation :

 -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,
                                            ),
                            ),



回答5:


You could use a FadeInImage with a placeholder to do it

When displaying images using the default Image widget, you might notice they simply pop onto the screen as they’re loaded. This might feel visually jarring to your users.

Instead, wouldn’t it be nice to display a placeholder at first, and images would fade in as they’re loaded? Use the FadeInImage widget for exactly this purpose.

FadeInImage works with images of any type: in-memory, local assets, or images from the internet.

You can also consider using local assets for placeholders. First, add the asset to the project’s pubspec.yaml file (for more details, see Adding assets and images):

Complete example

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final title = 'Fade in images';

    return MaterialApp(
      title: title,
      home: Scaffold(
        appBar: AppBar(
          title: Text(title),
        ),
        body: Center(
          child: FadeInImage.assetNetwork(
            placeholder: 'assets/loading.gif',
            image: 'https://picsum.photos/250?image=9',
          ),
        ),
      ),
    );
  }
}



来源:https://stackoverflow.com/questions/50759555/check-image-is-loaded-in-image-network-widget-in-flutter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!