How to control gif animation in Flutter?

Viewed 5975

I'm trying to restart an animated gif on Flutter. The gif image loads from network without a problem and animates after loading. I need to restart the animation on tapping a button.

Tried so far: - setState - change Key to some other unique key and setState to rebuild.

Solution as @chemamolins 's suggestion:

int _robotReloadCount=0;

....

GestureDetector(
onTap: () {
  onTapRobot();
},
child: Center(
  child: Container(
   margin: EdgeInsets.only(top: 55.0, bottom: 5.0),
   height: 150.0,
   width: 150.0,
   child:
    FadeInImage(
      key: this._robotImageKey,
      placeholder: AssetImage('assets/common/robot_placeholder.png'),
      image: NetworkImage(snapshot.data['robot_image_path'] +"robot_level" +snapshot.data['robot_level'].toString() +".gif"+"?"+this._robotReloadCount.toString()))),
  ),
),

....

onTapRobot() async{
    setState(() {
      this._robotReloadCount++;
    });
  }
1 Answers

I have done a lot of tests and it is not easy. The image is cached by the 'ImageProvider' and whatever you change or no matter the times you invoke build() the image is loaded from what is available in the cache.

So, apparently, you only have two options.

Either you rebuild with a new url, for instance by appending #whatever to the image url.

Or you remove the image from the cache as shown in the code below.

In either case you need to fetch again the image from the network.

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      home: new MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => new _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  String url = "https://media.giphy.com/media/hIfDZ869b7EHu/giphy.gif";

  void _evictImage() {
    final NetworkImage provider = NetworkImage(url);
    provider.evict().then<void>((bool success) {
      if (success) debugPrint('removed image!');
    });
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      body: new Center(
        child: Image.network(url),
      ),
      floatingActionButton: new FloatingActionButton(
        onPressed: _evictImage,
        child: new Icon(Icons.remove),
      ),
    );
  }
}
Related