Toast Animation In Flutter

Toast Animation In Flutter : This flutter tutorial post is show the toast animation in flutter.

AchievementView custom widget in flutter. Toast image display circle and round rectangle shape. alignment property is display toast top, bottom etc.

AchievementView(<br>
        context,<br>
        title: "",<br>
        subTitle: "",<br>
        //onTab: _onTabAchievement,<br>
        //icon: Icon(Icons.insert_emoticon, color: Colors.white,),<br>
        //typeAnimationContent: AnimationTypeAchievement.fadeSlideToUp,<br>
        //borderRadius: 5.0,<br>
        //color: Colors.blueGrey,<br>
        //textStyleTitle: TextStyle(),<br>
        //textStyleSubTitle: TextStyle(),<br>
        //alignment: Alignment.topCenter,<br>
        //duration: Duration(seconds: 3),<br>
        //isCircle: false,<br>
        listener: (status){<br>
          print(status);<br>
          //AchievementState.opening<br>
          //AchievementState.open<br>
          //AchievementState.closing<br>
          //AchievementState.closed<br>
        }<br>
   )..show();

Toast Animation In Flutter Screenshot :

Toast Animation In Flutter
Toast Animation In Flutter

achievement_view.dart

import 'package:flutter/material.dart';

import 'achievement_widget.dart';

class AchievementView {
  final BuildContext _context;
  final AlignmentGeometry alignment;
  final Duration duration;
  final GestureTapCallback onTab;
  final Function(AchievementState) listener;
  final bool isCircle;
  final Widget icon;
  final AnimationTypeAchievement typeAnimationContent;
  final double borderRadius;
  final Color color;
  final TextStyle textStyleTitle;
  final TextStyle textStyleSubTitle;
  final String title;
  final String subTitle;

  OverlayEntry _overlayEntry;

  AchievementView(
    this._context, {
    this.onTab,
    this.listener,
    this.isCircle = false,
    this.icon = const Icon(
      Icons.insert_emoticon,
      color: Colors.white,
    ),
    this.typeAnimationContent = AnimationTypeAchievement.fadeSlideToUp,
    this.borderRadius = 5.0,
    this.color = Colors.blueGrey,
    this.textStyleTitle,
    this.textStyleSubTitle,
    this.alignment = Alignment.topCenter,
    this.duration = const Duration(seconds: 3),
    this.title = "",
    this.subTitle = "",
  });

  OverlayEntry _buildOverlay() {
    return OverlayEntry(builder: (context) {
      return Align(
          alignment: alignment,
          child: AchievementWidget(
              title: title,
              subTitle: subTitle,
              duration: duration,
              listener: listener,
              onTab: onTab,
              isCircle: isCircle,
              textStyleSubTitle: textStyleSubTitle,
              textStyleTitle: textStyleTitle,
              icon: icon,
              typeAnimationContent: typeAnimationContent,
              borderRadius: borderRadius,
              color: color,
              finish: () {
                _hide();
              }));
    });
  }

  void show() {
    if (_overlayEntry == null) {
      _overlayEntry = _buildOverlay();
      Overlay.of(_context).insert(_overlayEntry);
    }
  }

  void _hide() {
    _overlayEntry?.remove();
    _overlayEntry = null;
  }
}

achievement_widget.dart

import 'package:flutter/material.dart';

enum AchievementState {
  opening,
  open,
  closing,
  closed,
}

enum AnimationTypeAchievement {
  fadeSlideToUp,
  fadeSlideToLeft,
  fade,
}

class AchievementWidget extends StatefulWidget {
  final Function() finish;
  final GestureTapCallback onTab;
  final Function(AchievementState) listener;
  final Duration duration;
  final bool isCircle;
  final Widget icon;
  final AnimationTypeAchievement typeAnimationContent;
  final double borderRadius;
  final Color color;
  final TextStyle textStyleTitle;
  final TextStyle textStyleSubTitle;
  final String title;
  final String subTitle;

  const AchievementWidget(
      {Key key,
      this.finish,
      this.duration = const Duration(seconds: 3),
      this.listener,
      this.isCircle = false,
      this.icon = const Icon(
        Icons.insert_emoticon,
        color: Colors.white,
      ),
      this.onTab,
      this.typeAnimationContent = AnimationTypeAchievement.fadeSlideToUp,
      this.borderRadius = 5.0,
      this.color = Colors.blueGrey,
      this.textStyleTitle,
      this.textStyleSubTitle,
      this.title = "",
      this.subTitle = ""})
      : super(key: key);

  @override
  AchievementWidgetState createState() => AchievementWidgetState();
}

class AchievementWidgetState extends State<AchievementWidget>
    with TickerProviderStateMixin {
  static const HEIGHT_CARD = 50.0;
  static const MARGIN_CARD = 20.0;
  static const ELEVATION_CARD = 2.0;

  AnimationController _controllerScale;
  CurvedAnimation _curvedAnimationScale;

  AnimationController _controllerSize;
  CurvedAnimation _curvedAnimationSize;

  AnimationController _controllerTitle;
  Animation<Offset> _titleSlideUp;

  AnimationController _controllerSubTitle;
  Animation<Offset> _subTitleSlideUp;

  @override
  void initState() {
    _controllerScale =
        AnimationController(vsync: this, duration: Duration(milliseconds: 300));
    _curvedAnimationScale =
        CurvedAnimation(parent: _controllerScale, curve: Curves.easeInOut)
          ..addStatusListener((status) {
            if (status == AnimationStatus.completed) {
              _controllerSize.forward();
            }
            if (status == AnimationStatus.dismissed) {
              _notifyListener(AchievementState.closed);
              widget.finish();
            }
          });

    _controllerSize =
        AnimationController(vsync: this, duration: Duration(milliseconds: 500))
          ..addStatusListener((status) {
            if (status == AnimationStatus.completed) {
              _controllerTitle.forward();
            }
            if (status == AnimationStatus.dismissed) {
              _controllerScale.reverse();
            }
          });
    _curvedAnimationSize =
        CurvedAnimation(parent: _controllerSize, curve: Curves.ease);

    _controllerTitle =
        AnimationController(vsync: this, duration: Duration(milliseconds: 250))
          ..addStatusListener((status) {
            if (status == AnimationStatus.completed) {
              _controllerSubTitle.forward();
            }
            if (status == AnimationStatus.dismissed) {
              _controllerSize.reverse();
            }
          });

    _titleSlideUp = _buildAnimatedContent(_controllerTitle);

    _controllerSubTitle =
        AnimationController(vsync: this, duration: Duration(milliseconds: 250))
          ..addStatusListener((status) {
            if (status == AnimationStatus.completed) {
              _notifyListener(AchievementState.open);
              _startTime();
            }
            if (status == AnimationStatus.dismissed) {
              _controllerTitle.reverse();
            }
          });

    _subTitleSlideUp = _buildAnimatedContent(_controllerSubTitle);
    super.initState();
    show();
  }

  void show() {
    _notifyListener(AchievementState.opening);
    _controllerScale.forward();
  }

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Container(
        height: HEIGHT_CARD,
        margin: EdgeInsets.all(MARGIN_CARD),
        child: ScaleTransition(
          scale: _curvedAnimationScale,
          child: _buildAchievement(),
        ),
      ),
    );
  }

  Widget _buildAchievement() {
    return Material(
        elevation: ELEVATION_CARD,
        borderRadius: _buildBorderCard(),
        color: widget.color,
        child: InkWell(
            onTap: () {
              if (widget.onTab != null) {
                widget?.onTab();
              }
            },
            child: Row(
              mainAxisSize: MainAxisSize.min,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: <Widget>[_buildIcon(), _buildContent()],
            )));
  }

  Widget _buildIcon() {
    return Container(
      width: HEIGHT_CARD,
      height: HEIGHT_CARD,
      decoration: BoxDecoration(
          color: Colors.white.withOpacity(0.2),
          borderRadius: _buildBorderIcon()),
      child: widget.icon,
    );
  }

  Widget _buildContent() {
    return Flexible(
        child: SizeTransition(
            sizeFactor: _curvedAnimationSize,
            axis: Axis.horizontal,
            child: Padding(
                padding: _buildPaddingContent(),
                child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: <Widget>[
                      _buildTitle(),
                      _buildSubTitle(),
                    ]))));
  }

  Widget _buildTitle() {
    return AnimatedBuilder(
        animation: _controllerTitle,
        builder: (_, child) {
          return SlideTransition(
            position: _titleSlideUp,
            child: FadeTransition(
              opacity: _controllerTitle,
              child: child,
            ),
          );
        },
        child: Text(
          widget.title,
          softWrap: true,
          style: TextStyle(color: Colors.white, fontWeight: FontWeight.bold)
              .merge(widget.textStyleTitle),
        ));
  }

  Widget _buildSubTitle() {
    return AnimatedBuilder(
        animation: _controllerSubTitle,
        builder: (_, child) {
          return SlideTransition(
            position: _subTitleSlideUp,
            child: FadeTransition(
              opacity: _controllerSubTitle,
              child: child,
            ),
          );
        },
        child: Text(
          widget.subTitle,
          maxLines: 1,
          style: TextStyle(color: Colors.white).merge(widget.textStyleSubTitle),
        ));
  }

  BorderRadiusGeometry _buildBorderIcon() {
    if (widget.isCircle) {
      return BorderRadius.all(Radius.circular(25.0));
    }
    return BorderRadius.only(
      topLeft: Radius.circular(widget.borderRadius),
      bottomLeft: Radius.circular(widget.borderRadius),
    );
  }

  BorderRadiusGeometry _buildBorderCard() {
    if (widget.isCircle) {
      return BorderRadius.all(Radius.circular(25.0));
    }
    return BorderRadius.all(Radius.circular(widget.borderRadius));
  }

  EdgeInsets _buildPaddingContent() {
    if (widget.isCircle) {
      return EdgeInsets.only(left: 15.0, right: 25.0);
    }
    return EdgeInsets.only(left: 15.0, right: 15.0);
  }

  Animation<Offset> _buildAnimatedContent(AnimationController controller) {
    double dx = 0.0;
    double dy = 0.0;
    switch (widget.typeAnimationContent) {
      case AnimationTypeAchievement.fadeSlideToUp:
        {
          dy = 2.0;
        }
        break;
      case AnimationTypeAchievement.fadeSlideToLeft:
        {
          dx = 2.0;
        }
        break;
      case AnimationTypeAchievement.fade:
        {}
        break;
    }
    return new Tween(begin: Offset(dx, dy), end: Offset(0.0, 0.0))
        .animate(CurvedAnimation(parent: controller, curve: Curves.decelerate));
  }

  void _notifyListener(AchievementState state) {
    if (widget.listener != null) {
      widget.listener(state);
    }
  }

  void _startTime() {
    Future.delayed(widget.duration, () {
      _notifyListener(AchievementState.closing);
      _controllerSubTitle.reverse();
    });
  }

  @override
  void dispose() {
    _controllerScale.dispose();
    _controllerSize.dispose();
    _controllerTitle.dispose();
    _controllerSubTitle.dispose();
    super.dispose();
  }
}

main.dart

import 'package:achievement_view/achievement_view.dart';
import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

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

class _MyHomePageState extends State<MyHomePage> {
  bool isCircle = false;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
       appBar: AppBar(title: Text('Toast animation')),
        body: Container(
            child: Center(
                child:
                    Column(mainAxisSize: MainAxisSize.min, children: <Widget>[
      Row(mainAxisSize: MainAxisSize.min, children: <Widget>[
        Checkbox(
            value: isCircle,
            onChanged: (change) {
              setState(() {
                isCircle = change;
              });
            }),
        Text("isCircle")
      ]),
      RaisedButton(
          child: Text("Show"),
          onPressed: () {
            show(context);
          })
    ]))));
  }

  void show(BuildContext context) {
    AchievementView(context,
        title: "Title",
        borderRadius: 0.5,
        color: Colors.blueGrey,
        alignment: Alignment.topCenter,
        duration: Duration(seconds: 1),
        subTitle: "Flutter tutorial",
        isCircle: isCircle, listener: (status) {
      print(status);
    })
      ..show();
  }
}

The flutter tutorial  is a website that bring you the latest and amazing resources of code. All the languages codes are included in this website. The languages like flutter, android, java,kotlin etc.with the help of this languages any user can develop the beautiful application

For more information about Flutter. visit www.fluttertutorial.in