Skip to content

Commit 547fb51

Browse files
committed
fix: fix top-level snack bar
Restore with global key.
1 parent a673b1a commit 547fb51

File tree

3 files changed

+14
-5
lines changed

3 files changed

+14
-5
lines changed

lib/app.dart

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -489,6 +489,7 @@ class _AppState extends State<App> with WindowListener, LoggerMixin {
489489
theme: lightTheme,
490490
darkTheme: darkTheme,
491491
themeMode: ThemeMode.values[themeModeIndex],
492+
scaffoldMessengerKey: snackbarKey,
492493
);
493494
},
494495
),

lib/instance.dart

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import 'dart:ui' as ui;
22

3+
import 'package:flutter/material.dart';
34
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
45
import 'package:get_it/get_it.dart';
56
import 'package:talker_flutter/talker_flutter.dart';
@@ -30,3 +31,11 @@ late final FlutterLocalNotificationsPlugin flnp;
3031
Future<ui.ImmutableBuffer> getPlaceholderImageData() async {
3132
return ui.ImmutableBuffer.fromAsset(assetPlaceholderImagePath);
3233
}
34+
35+
/// The global snackbar key.
36+
///
37+
/// Because we have global BlocListeners outside of `MaterialApp` that calls `showSnackBar`, use this global key to
38+
/// access a context with `Scaffold` to show the snack bar.
39+
///
40+
/// Do NOT use this global key directly, call `showSnackBar` function instead.
41+
final GlobalKey<ScaffoldMessengerState> snackbarKey = GlobalKey<ScaffoldMessengerState>();

lib/utils/show_toast.dart

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import 'package:flutter/material.dart';
22
import 'package:tsdm_client/i18n/strings.g.dart';
3+
import 'package:tsdm_client/instance.dart';
34

45
/// Show a snack bar contains message show no more contents.
56
void showNoMoreSnackBar(BuildContext context, {bool floating = true}) {
@@ -21,8 +22,6 @@ void showSnackBar({
2122
required String message,
2223
bool floating = true,
2324
SnackBarAction? action,
24-
}) {
25-
ScaffoldMessenger.of(context).showSnackBar(
26-
SnackBar(behavior: floating ? SnackBarBehavior.floating : null, content: Text(message), action: action),
27-
);
28-
}
25+
}) => snackbarKey.currentState?.showSnackBar(
26+
SnackBar(behavior: floating ? SnackBarBehavior.floating : null, content: Text(message), action: action),
27+
);

0 commit comments

Comments
 (0)