Skip to content

Commit

Permalink
hide snackbar when route change
Browse files Browse the repository at this point in the history
  • Loading branch information
Predidit committed Dec 15, 2024
1 parent e44a68a commit 49942f7
Showing 1 changed file with 21 additions and 15 deletions.
36 changes: 21 additions & 15 deletions lib/bean/dialog/dialog_helper.dart
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import 'package:flutter/material.dart';
// A simple dialog helper class to show dialogs and toasts based on flutter native implementation (replace flutter_smart_dialog)
// flutter_smart_dialog use overlays and self-managed route stack to show dialogs.
// It's powerful but can't behave like the default showDialog, e.g. the lack of mask animation. the lack of snackbar.
// Use the implementation should be careful, because shared route stack with the whole app, it may cause some unexpected behaviors.
// Use the implementation should be careful, because shared route stack with the whole app, it may cause some unexpected behaviors.
// Don't use it in double PopScope widget.
class KazumiDialog {
static final KazumiDialogObserver _observer =
Expand Down Expand Up @@ -42,20 +42,18 @@ class KazumiDialog {
}) {
final scaffoldContext = context ?? _observer.currentContext;
if (scaffoldContext != null) {
ScaffoldMessenger.of(scaffoldContext)
..hideCurrentSnackBar()
..showSnackBar(
SnackBar(
content: Text(message),
duration: duration,
action: showUndoButton
? SnackBarAction(
label: 'Dismiss',
onPressed: () {},
)
: null,
),
);
ScaffoldMessenger.of(scaffoldContext).showSnackBar(
SnackBar(
content: Text(message),
duration: duration,
action: showUndoButton
? SnackBarAction(
label: 'Dismiss',
onPressed: () {},
)
: null,
),
);
} else {
debugPrint(
'Kazumi Dialog Error: No Scaffold context available to show Toast');
Expand Down Expand Up @@ -130,6 +128,7 @@ class KazumiDialogObserver extends NavigatorObserver {
@override
void didPush(Route<dynamic> route, Route<dynamic>? previousRoute) {
super.didPush(route, previousRoute);
_removeCurrentSnackBar(previousRoute);
if (_isKazumiDialogRoute(route)) {
_kazumiDialogRoutes.add(route);
currentContext = route.navigator?.context;
Expand All @@ -141,6 +140,7 @@ class KazumiDialogObserver extends NavigatorObserver {
@override
void didPop(Route<dynamic> route, Route<dynamic>? previousRoute) {
super.didPop(route, previousRoute);
_removeCurrentSnackBar(route);
if (_isKazumiDialogRoute(route)) {
_kazumiDialogRoutes.remove(route);
}
Expand All @@ -157,4 +157,10 @@ class KazumiDialogObserver extends NavigatorObserver {
bool _isKazumiDialogRoute(Route<dynamic> route) {
return route.settings.name == 'KazumiDialog';
}

void _removeCurrentSnackBar(Route<dynamic>? route) {
if (route?.navigator?.context != null) {
ScaffoldMessenger.of(route!.navigator!.context).removeCurrentSnackBar();
}
}
}

0 comments on commit 49942f7

Please sign in to comment.