i want to know the screen(StatelessWidget) is in front or background. for now, a screen in background shows AlertDialog, but i want to show the dialog only when the screen is in front. is there any way to do that?
here's my code using hooks_riverpod. i omitted some lines because of "mostly code" warning.
final _provider = provider801x;
class MyPage801x extends HookConsumerWidget {
MyPage801x({Key? key}) : super(key: key);
@override
Widget build(BuildContext context, WidgetRef ref) {
final String? message = ref.watch(_provider).message;
if (message != null) {
ref.read(_provider).done();
showResult(context, message); //don't want to show when in background.
}
return Scaffold(
appBar: AppBar(
title: Text('main screen'),
),
body: Container(),
);
}
Future<void> showResult(BuildContext context, String message) async {
Future.delayed(Duration(milliseconds: 500), () async {
await showOKOnlyDialog(context, message: message);
});
}
}
final provider801x = ChangeNotifierProvider.autoDispose((ref) => Notifier801x(ref));
class Notifier801x extends ChangeNotifier {
Notifier801x(this._ref) {
_iapManager = IAPManager4Android();
_refreshDataset();
_iapListener = _iapManager.onChangedIAP.listen((IAPTransactionStateEnum state) async {
_message = state.message! ' @801x';
notifyListeners();
});
}
String? _message = null;
String? get message => _message;
void done() {
_message = null;
}
void _refreshDataset() {
//fetch data
notifyListeners();
}
}
CodePudding user response:
You could use mounted
for this case.
mounted
is true if the widget is visible to the user or technically on the top of the stack of screens otherwise will be false.
So, you can use it like this way
if(mounted){
//do your stuff like show dialog or snackbar
}
CodePudding user response:
Use a static string (or DI ) in main function , set it to class name in build function of any screen. check this variable to know which screen is visible.
CodePudding user response:
this code worked!
if (ModalRoute.of(context)?.isCurrent ?? false) {
showResult(context, message);
}
I got this answer from the page below. thank you all!
Flutter | How to know if widget is on top of navigation stack (visible)