1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
| import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart';
class Toast { static OverlayEntry _overlayEntry; static bool _showing = false; static DateTime _startedTime; static String _msg; static int _showTime; static Color _bgColor; static Color _textColor; static double _textSize; static String _toastPosition; static double _pdHorizontal; static double _pdVertical; static void toast( BuildContext context, { String msg, int showTime = 2000, Color bgColor = Colors.black, Color textColor = Colors.white, double textSize = 14.0, String position = 'center', double pdHorizontal = 20.0, double pdVertical = 10.0, }) async { assert(msg != null); _msg = msg; _startedTime = DateTime.now(); _showTime = showTime; _bgColor = bgColor; _textColor = textColor; _textSize = textSize; _toastPosition = position; _pdHorizontal = pdHorizontal; _pdVertical = pdVertical; OverlayState overlayState = Overlay.of(context); _showing = true; if (_overlayEntry == null) { _overlayEntry = OverlayEntry( builder: (BuildContext context) => Positioned( top: _calToastPosition(context), child: Container( alignment: Alignment.center, width: MediaQuery.of(context).size.width, child: Padding( padding: EdgeInsets.symmetric(horizontal: 40.0), child: AnimatedOpacity( opacity: _showing ? 1.0 : 0.0, duration: _showing ? Duration(milliseconds: 100) : Duration(milliseconds: 400), child: _buildToastWidget(), ), )), )); overlayState.insert(_overlayEntry); } else { _overlayEntry.markNeedsBuild(); } await Future.delayed(Duration(milliseconds: _showTime));
if (DateTime.now().difference(_startedTime).inMilliseconds >= _showTime) { _showing = false; _overlayEntry.markNeedsBuild(); await Future.delayed(Duration(milliseconds: 400)); _overlayEntry.remove(); _overlayEntry = null; } }
static _buildToastWidget() { return Center( child: Card( color: _bgColor, child: Padding( padding: EdgeInsets.symmetric( horizontal: _pdHorizontal, vertical: _pdVertical), child: Text( _msg, style: TextStyle( fontSize: _textSize, color: _textColor, ), ), ), ), ); }
static _calToastPosition(context) { var backResult; if (_toastPosition == 'top') { backResult = MediaQuery.of(context).size.height * 1 / 4; } else if (_toastPosition == 'center') { backResult = MediaQuery.of(context).size.height * 2 / 5; } else { backResult = MediaQuery.of(context).size.height * 3 / 4; } return backResult; } }
|