How i prevent loading image multiple time?

1

In my flutter application there is list of posts. Post may have multiple images. I have used buttons to navigate to next and previous.Every time when i click button to navigate to next/previous images it takes some time to load. I want to load all images at once so that when i click button to navigate to next/previous image, it should available without any delay. As I have observed that in Instagram app when there is more than one images in a post we can navigate to next/previous image without any delay.

class SuggestPostListItem extends StatefulWidget {
  final SuggestPostBeen item;
  final int index;
  String userName;
  String userImage;
  SuggestPostListItem({
    @required this.index,
    @required this.item,
    @required this.userName,
    @required this.userImage,
  });
  @override
  SuggestPostListItemState createState() => new SuggestPostListItemState();
}

class SuggestPostListItemState extends State<SuggestPostListItem> {
  var _imageCount;
  @override
  void initState() {
    _imageCount = widget.item.media_list.length;
    // TODO: implement initState
    setStatus();

    super.initState();
  }

  int traker = 0;
  int _imageIndex = 0;
  Widget showLeftButton() {
    return _imageCount > 1 && traker > 0
        ? IconButton(
            icon: Icon(Icons.arrow_back_ios),
            onPressed: () {
              setState(() {
                print("left clicked $traker");
                traker = traker - 1;
                _imageIndex = traker;
              });
            },
            color: Colors.white,
          )
        : Container();
  }

  Widget showRightButton() {
    return _imageCount > 1 && traker < _imageCount - 1
        ? IconButton(
            icon: Icon(Icons.arrow_forward_ios),
            onPressed: () {
              setState(() {
                print("right clicked $traker");
                traker = traker + 1;
                _imageIndex = traker < _imageCount ? traker : traker - 1;
              });
            },
            color: Colors.white,
          )
        : Container();
  }

  Widget _loadImage(int index) {
    return FadeInImage.assetNetwork(
        fit: BoxFit.fitHeight,
        image: _imageCount > 0 ? widget.item.media_list[index]["imageUrl"] : "",
        placeholder: 'images/dummi_rect.png');
  }

  @override
  Widget build(BuildContext context) {
    return _buildTextContainer();
  }

  Widget _buildTextContainer() {
    Widget upperSectionWidget = new Container(
      child: new Row(
        mainAxisAlignment: MainAxisAlignment.start,
        children: <Widget>[
          new Expanded(
            child: new ListTile(
              contentPadding: const EdgeInsets.only(left: 10.0),
              leading: new Container(
                width: 30.0,
                height: 30.0,
                child: new CircularLabelImage(
                  radious: 30.0,
                  textValue: widget.userName,
                  imageUrl: widget.userImage,
                ),
              ),
              title: new Text(widget.userName,
                  style: TextStyle(color: Colors.black, fontSize: 20.0)),
              subtitle: new Text(DateUtil.getDate(widget.item.created_at),
                  style: TextStyle(fontSize: 14.0)),
            ),
          ),
        ],
      ),
    );

//    var postImage = FadeInImage.assetNetwork(
//        fit: BoxFit.fitHeight,
//        image:widget.item.image_url,
//        placeholder: 'images/dummi_rect.png');

    //enhancement to show horizontal list
//    var postImage=FadeInImage.assetNetwork(
//
//        fit: BoxFit.fitHeight,
//        image:_imageCount>0?widget.item.media_list[_imageIndex]["imageUrl"]:"",
//        placeholder: 'images/dummi_rect.png');

    var imageOverlayGradient = DecoratedBox(
      decoration: BoxDecoration(
        gradient: LinearGradient(
          begin: FractionalOffset.topCenter,
          end: FractionalOffset.bottomCenter,
          colors: [
            const Color(0x80000000),
            const Color(0x20000000),
          ],
        ),
      ),
    );
    Widget listItem = new Container(
      child: new Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          upperSectionWidget,
          new Container(
            height: 200.0,
            width: double.infinity,
            child: new Material(
              type: MaterialType.card,
              // elevation: 8.0,
              // borderRadius: new BorderRadius.only(topLeft: const Radius.circular(8.0), topRight: const Radius.circular(8.0)),
              child: new Stack(
                //if fit not specified then, it aligns to top left....
                fit: StackFit.expand,
                children: <Widget>[
                  Positioned.fill(
                      top: 0.0,
                      child: new Parallax.inside(
                        child: _loadImage(
                            _imageIndex), //new Image.network('https://flutter.io/images/homepage/header-illustration.png'),
                        mainAxisExtent: 150.0,
                      ) //new ParalllexImageWidget(imageUrl: result.imageUrl,controller: controller,)
                      ),
                  imageOverlayGradient,
                  Positioned(
                    top: 10.0,
                    bottom: 10.0,
                    left: 10.0,
                    right: 10.0,
                    child: new Text(
                      widget.item.title,
                      style: TextStyle(color: Colors.white, fontSize: 20.0),
                      overflow: TextOverflow.ellipsis,
                    ),
                  ),
                  new Positioned(
                    bottom: 10.0,
                    right: 10.0,
                    child: new Chip(
                      label: new Text(status,
                          style: new TextStyle(
                            fontSize: 14.0,
                            color: Colors.white,
                          )),
                      backgroundColor: statusColor,
                    ),
                  ),
                  Positioned(
                    left: 0,
                    height: 200,
                    child: showLeftButton(),
                  ),
                  Positioned(right: 0, height: 200, child: showRightButton()),
                ],
              ),
            ),
          ),
          new Container(
            padding: const EdgeInsets.all(10.0),
            child: new Text(widget.item.description,
                style: TextStyle(fontSize: 16.0)),
          ),
          isPointsVisible ? getActionsList() : new Container(),
        ],
      ),
    );

    return new Container(
        child: new Container(
            padding: EdgeInsets.only(top: 10.0),
            child: new Material(
              type: MaterialType.card,
              elevation: 2.0,
              borderRadius: new BorderRadius.circular(8.0),
              child: listItem,
            )));
  }

  Widget getActionsList() {
    return new Container(
      height: 77.0,
      color: Colors.white,
      child: new Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: [
          buildButtonColumn(
              context, 'images/share.png', 'Shares', widget.item.post_share),
          buildButtonColumn(
              context, 'images/clicks.png', 'Clicks', widget.item.post_click),
          buildButtonColumn(context, 'images/reaction.png', 'Recations',
              widget.item.post_reactions),
          buildButtonColumn(
              context, 'images/view.png', 'View', widget.item.post_view),
        ],
      ),
    );
  }

  Column buildButtonColumn(
      BuildContext context, String iconPath, String label, int points) {
    return new Column(
      mainAxisSize: MainAxisSize.min,
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        new IconButton(
          icon: Image(
            image: new AssetImage(iconPath),
            width: 20.0,
            height: 20.0,
          ),
          iconSize: 20.0,
        ),
        /*new Container(
          child: new Text(
            label,
            style: new TextStyle(
              fontSize: 16.0,
              fontWeight: FontWeight.w400,
              color: Colors.black54,
            ),
          ),
        ),*/
        new Text(
          points.toString(),
          style: new TextStyle(
            fontSize: 16.0,
            fontWeight: FontWeight.w400,
            color: Colors.black54,
          ),
        ),
        new Container(
          height: 10.0,
        ),
      ],
    );
  }

  var statusColor;
  String status;
  bool isPointsVisible = false;
  setStatus() {
    switch (widget.item.status) {
      case 24:
        statusColor = Colors.orange;
        status = 'Pending';
        break;
      case 25:
        statusColor = Colors.red;
        status = 'Excluded';
        break;
      case 26:
        statusColor = Colors.blue;
        status = 'Schedule';
        break;
      case 27:
        statusColor = Colors.green;
        status = 'Published';
        isPointsVisible = true;
        break;
    }
  }
}
flutter
dart
asked on Stack Overflow Jul 2, 2019 by Dhanraj Verma

1 Answer

0

You can use https://pub.dev/packages/cached_network_image so that it loads a cached version of the image if it was already fetched.

answered on Stack Overflow Jul 3, 2019 by Martyns

User contributions licensed under CC BY-SA 3.0