Hero tag example code in Flutter



Hero widget is used to animate a widget from one screen to other screen.


It is quite easy to animate a widget with the Here widget, to do this you need three steps only

1. Create Two screen with the same widget
2. Create a Hero widget at first screen
3. Create a Hero widget at second screen

 

Here is the complete example


class NetworkDiagnosis extends StatefulWidget {
  @override
  _NetworkDiagnosisState createState() => _NetworkDiagnosisState();
}

class _NetworkDiagnosisState extends State<NetworkDiagnosis> {

  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: AppTheme.appBarColor,
        title: const Text('Hero Widget'),
      ),
      body: Center(
        child: AnimateImage(
          imageUrl: "assets/mode_cool/mode_cool_3.png",
          size: 200.0,
          onTap: () {
            Navigator.of(context).push(MaterialPageRoute<void>(
                builder: (BuildContext context) {
                  return Scaffold(
                    appBar: AppBar(
                      backgroundColor: AppTheme.appBarColor,
                      title: const Text('Hero Animation'),
                    ),
                    body: Container(
                      alignment: Alignment.topLeft,
                      child: AnimateImage(
                        imageUrl: "assets/mode_cool/mode_cool_3.png",
                        size: 100.0,
                        onTap: () {
                          Navigator.of(context).pop();
                        },
                      ),
                    ),
                  );
                }
            ));
          },
        ),
      ),
    );
  }
}


AnimateImage.dart


class AnimateImage extends StatelessWidget {
  final String imageUrl;
  final dynamic onTap;
  final double size;

  AnimateImage({Key key, this.imageUrl, this.onTap, this.size}) : super(key: key);

  Widget build(BuildContext context) {
    return SizedBox(
      width: size, //You can change the size dynamically
      child: Hero(
        tag: imageUrl,
        child: Material(
          child: InkWell(
            onTap: onTap,
            child: Image.asset(imageUrl),
          ),
        ),
      ),
    );
  }
}




How it looks like after run










Previous
Next Post »