-
-
Notifications
You must be signed in to change notification settings - Fork 369
/
Copy pathfluttertoast.dart
449 lines (401 loc) · 12.7 KB
/
fluttertoast.dart
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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
import 'dart:async';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
/// Signature for a function that defines custom position mapping for a toast
///
/// [child] is the toast widget to be positioned.
/// [gravity] is the gravity option for the toast which can be used to determine the position.
/// The function should return a [Widget] that defines the position of the toast.
/// If the position is not handled by the custom logic, return `null` to fall back to default logic.
typedef ToastPositionMapping = Widget? Function(
Widget child, ToastGravity? gravity);
/// Toast Length
/// Only for Android Platform
enum Toast {
/// Show Short toast for 1 sec
LENGTH_SHORT,
/// Show Long toast for 5 sec
LENGTH_LONG
}
/// ToastGravity
/// Used to define the position of the Toast on the screen
enum ToastGravity {
TOP,
BOTTOM,
CENTER,
TOP_LEFT,
TOP_RIGHT,
BOTTOM_LEFT,
BOTTOM_RIGHT,
CENTER_LEFT,
CENTER_RIGHT,
SNACKBAR,
NONE
}
/// Plugin to show a toast message on screen
/// Only for android, ios and Web platforms
class Fluttertoast {
/// [MethodChannel] used to communicate with the platform side.
static const MethodChannel _channel =
const MethodChannel('PonnamKarthik/fluttertoast');
/// Let say you have an active show
/// Use this method to hide the toast immediately
static Future<bool?> cancel() async {
bool? res = await _channel.invokeMethod("cancel");
return res;
}
/// Show the [msg] via native platform's toast.
///
/// On Android uses Toast.
/// On iOS uses https://github.com/scalessec/Toast plugin.
/// On web uses https://github.com/apvarun/toastify-js library.
///
/// Parameter [msg] is required and all remaining are optional.
///
/// The [fontAsset] is the path to your Flutter asset to use in toast.
/// If not specified platform's default font will be used.
static Future<bool?> showToast({
required String msg,
Toast? toastLength,
int timeInSecForIosWeb = 1,
double? fontSize,
String? fontAsset,
ToastGravity? gravity,
Color? backgroundColor,
Color? textColor,
bool webShowClose = false,
webBgColor = "linear-gradient(to right, #00b09b, #96c93d)",
webPosition = "right",
}) async {
String toast = "short";
if (toastLength == Toast.LENGTH_LONG) {
toast = "long";
}
String gravityToast = "bottom";
if (gravity == ToastGravity.TOP) {
gravityToast = "top";
} else if (gravity == ToastGravity.CENTER) {
gravityToast = "center";
} else {
gravityToast = "bottom";
}
if (backgroundColor == null && Platform.isIOS) {
backgroundColor = Colors.black;
}
if (textColor == null && Platform.isIOS) {
textColor = Colors.white;
}
final Map<String, dynamic> params = <String, dynamic>{
'msg': msg,
'length': toast,
'time': timeInSecForIosWeb,
'gravity': gravityToast,
'bgcolor': backgroundColor?.value,
'iosBgcolor': backgroundColor?.value,
'textcolor': textColor?.value,
'iosTextcolor': textColor?.value,
'fontSize': fontSize,
'fontAsset': fontAsset,
'webShowClose': webShowClose,
'webBgColor': webBgColor,
'webPosition': webPosition
};
bool? res = await _channel.invokeMethod('showToast', params);
return res;
}
}
/// Signature for a function to buildCustom Toast
typedef PositionedToastBuilder = Widget Function(
BuildContext context, Widget child, ToastGravity? gravity);
/// Runs on dart side this has no interaction with the Native Side
/// Works with all platforms just in two lines of code
/// final fToast = FToast().init(context)
/// fToast.showToast(child)
///
class FToast {
BuildContext? context;
static final FToast _instance = FToast._internal();
/// Prmary Constructor for FToast
factory FToast() {
return _instance;
}
/// Take users Context and saves to avariable
FToast init(BuildContext context) {
_instance.context = context;
return _instance;
}
FToast._internal();
OverlayEntry? _entry;
List<_ToastEntry> _overlayQueue = [];
Timer? _timer;
Timer? _fadeTimer;
/// Internal function which handles the adding
/// the overlay to the screen
///
_showOverlay() {
if (_overlayQueue.isEmpty) {
_entry = null;
return;
}
if (context == null) {
/// Need to clear queue
removeQueuedCustomToasts();
throw ("Error: Context is null, Please call init(context) before showing toast.");
}
/// To prevent exception "Looking up a deactivated widget's ancestor is unsafe."
/// which can be thrown if context was unmounted (e.g. screen with given context was popped)
/// TODO: revert this change when envoirment will be Flutter >= 3.7.0
// if (context?.mounted != true) {
// if (kDebugMode) {
// print(
// 'FToast: Context was unmuted, can not show ${_overlayQueue.length} toast.');
// }
// /// Need to clear queue
// removeQueuedCustomToasts();
// return; // Or maybe thrown error too
// }
OverlayState? _overlay;
try {
_overlay = Overlay.of(context!);
} catch (err) {
removeQueuedCustomToasts();
throw ("""Error: Overlay is null.
Please don't use top of the widget tree context (such as Navigator or MaterialApp) or
create overlay manually in MaterialApp builder.
More information
- https://github.com/ponnamkarthik/FlutterToast/issues/393
- https://github.com/ponnamkarthik/FlutterToast/issues/234""");
}
/// Create entry only after all checks
_ToastEntry _toastEntry = _overlayQueue.removeAt(0);
_entry = _toastEntry.entry;
_overlay.insert(_entry!);
_timer = Timer(_toastEntry.duration, () {
_fadeTimer = Timer(_toastEntry.fadeDuration, () {
removeCustomToast();
});
});
}
/// If any active toast present
/// call removeCustomToast to hide the toast immediately
removeCustomToast() {
_timer?.cancel();
_fadeTimer?.cancel();
_timer = null;
_fadeTimer = null;
_entry?.remove();
_entry = null;
_showOverlay();
}
/// FToast maintains a queue for every toast
/// if we called showToast for 3 times we all to queue
/// and show them one after another
///
/// call removeCustomToast to hide the toast immediately
removeQueuedCustomToasts() {
_timer?.cancel();
_fadeTimer?.cancel();
_timer = null;
_fadeTimer = null;
_overlayQueue.clear();
_entry?.remove();
_entry = null;
}
/// showToast accepts all the required paramenters and prepares the child
/// calls _showOverlay to display toast
///
/// Paramenter [child] is requried
/// toastDuration default is 2 seconds
/// fadeDuration default is 350 milliseconds
void showToast({
required Widget child,
PositionedToastBuilder? positionedToastBuilder,
Duration toastDuration = const Duration(seconds: 2),
ToastGravity? gravity,
Duration fadeDuration = const Duration(milliseconds: 350),
bool ignorePointer = false,
bool isDismissible = false,
}) {
if (context == null)
throw ("Error: Context is null, Please call init(context) before showing toast.");
Widget newChild = _ToastStateFul(
child,
toastDuration,
fadeDuration,
ignorePointer,
!isDismissible
? null
: () {
removeCustomToast();
});
/// Check for keyboard open
/// If open will ignore the gravity bottom and change it to center
if (gravity == ToastGravity.BOTTOM) {
if (MediaQuery.of(context!).viewInsets.bottom != 0) {
gravity = ToastGravity.CENTER;
}
}
OverlayEntry newEntry = OverlayEntry(builder: (context) {
if (positionedToastBuilder != null)
return positionedToastBuilder(context, newChild, gravity);
return _getPositionWidgetBasedOnGravity(newChild, gravity);
});
_overlayQueue.add(_ToastEntry(
entry: newEntry, duration: toastDuration, fadeDuration: fadeDuration));
if (_timer == null) _showOverlay();
}
/// _getPositionWidgetBasedOnGravity generates [Positioned] [Widget]
/// based on the gravity [ToastGravity] provided by the user in
/// [showToast]
_getPositionWidgetBasedOnGravity(Widget child, ToastGravity? gravity) {
switch (gravity) {
case ToastGravity.TOP:
return Positioned(top: 100.0, left: 24.0, right: 24.0, child: child);
case ToastGravity.TOP_LEFT:
return Positioned(top: 100.0, left: 24.0, child: child);
case ToastGravity.TOP_RIGHT:
return Positioned(top: 100.0, right: 24.0, child: child);
case ToastGravity.CENTER:
return Positioned(
top: 50.0, bottom: 50.0, left: 24.0, right: 24.0, child: child);
case ToastGravity.CENTER_LEFT:
return Positioned(top: 50.0, bottom: 50.0, left: 24.0, child: child);
case ToastGravity.CENTER_RIGHT:
return Positioned(top: 50.0, bottom: 50.0, right: 24.0, child: child);
case ToastGravity.BOTTOM_LEFT:
return Positioned(bottom: 50.0, left: 24.0, child: child);
case ToastGravity.BOTTOM_RIGHT:
return Positioned(bottom: 50.0, right: 24.0, child: child);
case ToastGravity.SNACKBAR:
return Positioned(
bottom: MediaQuery.of(context!).viewInsets.bottom,
left: 0,
right: 0,
child: child);
case ToastGravity.NONE:
return Positioned.fill(child: child);
case ToastGravity.BOTTOM:
default:
return Positioned(bottom: 50.0, left: 24.0, right: 24.0, child: child);
}
}
}
/// Simple builder method to create a [TransitionBuilder]
/// and for the use in MaterialApp builder method
// ignore: non_constant_identifier_names
TransitionBuilder FToastBuilder() {
return (context, child) {
return _FToastHolder(
child: child!,
);
};
}
/// Simple StatelessWidget which holds the child
/// and creates an [Overlay] to display the toast
class _FToastHolder extends StatelessWidget {
const _FToastHolder({Key? key, required this.child}) : super(key: key);
final Widget child;
@override
Widget build(BuildContext context) {
return Overlay(
initialEntries: <OverlayEntry>[
OverlayEntry(
builder: (BuildContext ctx) {
return child;
},
),
],
);
}
}
/// internal class [_ToastEntry] which maintains
/// each [OverlayEntry] and [Duration] for every toast user
/// triggered
class _ToastEntry {
final OverlayEntry entry;
final Duration duration;
final Duration fadeDuration;
_ToastEntry({
required this.entry,
required this.duration,
required this.fadeDuration,
});
}
/// internal [StatefulWidget] which handles the show and hide
/// animations for [FToast]
class _ToastStateFul extends StatefulWidget {
_ToastStateFul(this.child, this.duration, this.fadeDuration,
this.ignorePointer, this.onDismiss,
{Key? key})
: super(key: key);
final Widget child;
final Duration duration;
final Duration fadeDuration;
final bool ignorePointer;
final VoidCallback? onDismiss;
@override
ToastStateFulState createState() => ToastStateFulState();
}
/// State for [_ToastStateFul]
class ToastStateFulState extends State<_ToastStateFul>
with SingleTickerProviderStateMixin {
/// Start the showing animations for the toast
showIt() {
_animationController!.forward();
}
/// Start the hidding animations for the toast
hideIt() {
_animationController!.reverse();
_timer?.cancel();
}
/// Controller to start and hide the animation
AnimationController? _animationController;
late Animation _fadeAnimation;
Timer? _timer;
@override
void initState() {
_animationController = AnimationController(
vsync: this,
duration: widget.fadeDuration,
);
_fadeAnimation =
CurvedAnimation(parent: _animationController!, curve: Curves.easeIn);
super.initState();
showIt();
_timer = Timer(widget.duration, () {
hideIt();
});
}
@override
void deactivate() {
_timer?.cancel();
_animationController!.stop();
super.deactivate();
}
@override
void dispose() {
_timer?.cancel();
_animationController?.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: widget.onDismiss == null ? null : () => widget.onDismiss!(),
behavior: HitTestBehavior.translucent,
child: IgnorePointer(
ignoring: widget.ignorePointer,
child: FadeTransition(
opacity: _fadeAnimation as Animation<double>,
child: Center(
child: Material(
color: Colors.transparent,
child: widget.child,
),
),
),
),
);
}
}