Skip to content

Instantly share code, notes, and snippets.

@darmawan01
Created September 8, 2021 04:03
Show Gist options
  • Save darmawan01/9ec9c7df46f6be07c9335dccba6af9fd to your computer and use it in GitHub Desktop.
Save darmawan01/9ec9c7df46f6be07c9335dccba6af9fd to your computer and use it in GitHub Desktop.
Custom Toast - Flutter
import 'dart:async';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
class CustomToast {
static OverlayEntry _overlayEntry;
static OverlayEntry _overlayEntry1;
static bool isVisible = false;
static Timer _timer;
static void show({
BuildContext context,
String msg,
Color backgroundColor = Colors.white,
TextStyle textStyle,
int closeDuratioin = 5,
}) {
dismiss();
CustomToast._createView(
context,
msg,
backgroundColor,
textStyle,
closeDuratioin,
);
}
static void _createView(
BuildContext context,
String msg,
Color background,
TextStyle textStyle,
int closeDuratioin,
) async {
var overlayState = Overlay.of(context);
final themeData = Theme.of(context);
_overlayEntry = OverlayEntry(
builder: (BuildContext context) => _ToastAnimatedWidget(
child: Container(
width: MediaQuery.of(context).size.width,
child: Container(
alignment: Alignment.center,
width: MediaQuery.of(context).size.width,
child: Container(
decoration: BoxDecoration(
color: background,
borderRadius: BorderRadius.circular(20),
),
margin: EdgeInsets.symmetric(horizontal: 20),
padding: EdgeInsets.fromLTRB(16, 10, 16, 10),
child: Text(
msg,
softWrap: true,
style: themeData.textTheme.bodyText1.copyWith(
color: textStyle.color,
fontSize: textStyle.fontSize,
),
textAlign: TextAlign.center,
),
),
),
),
),
);
_overlayEntry1 = OverlayEntry(
builder: (BuildContext context) => Container(
height: MediaQuery.of(context).size.height,
width: MediaQuery.of(context).size.width,
color: Colors.black.withOpacity(0.4),
),
);
isVisible = true;
overlayState.insertAll([_overlayEntry1, _overlayEntry]);
// Clear automatocally after 5 second default
_timer = Timer(Duration(seconds: closeDuratioin), () {
CustomToast.dismiss();
});
}
static dismiss() async {
if (!isVisible) {
return;
}
isVisible = false;
_overlayEntry?.remove();
_overlayEntry1?.remove();
_timer?.cancel();
}
}
class _ToastAnimatedWidget extends StatefulWidget {
_ToastAnimatedWidget({
Key key,
@required this.child,
}) : super(key: key);
final Widget child;
@override
_ToastWidgetState createState() => _ToastWidgetState();
}
class _ToastWidgetState extends State<_ToastAnimatedWidget>
with SingleTickerProviderStateMixin {
bool get _isVisible => true; //update this value later
@override
void initState() {
super.initState();
}
@override
Widget build(BuildContext context) {
return Positioned(
bottom: 50,
child: AnimatedOpacity(
duration: Duration(seconds: 2),
curve: Curves.easeInOut,
opacity: _isVisible ? 1.0 : 0.0,
child: widget.child,
),
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment