admin管理员组文章数量:1287513
Right now I have
return PopScope(
canPop: false,
onPopInvokedWithResult: (bool didPop, Object? result) async {
if (result == null){
final navigator = Navigator.of(context);
await _save();
navigator.pop(true);
}
},
which works, but I'm uncertain it's reliable. That is because _save() depends on fetching information from the widget tree. I also dislike how I interpret catch system pops by checking that result == null. Again, it seems unreliable. I'm also not sure if the function being async is acceptable.
Is there a straightforward, standard way to intercept pops, WHILE the widget tree is still available. Bonus Question: is there a way to intercept pushes?
(I also fot to mention that this approach messes up a feature which depends on Navigator.popUntil())
Right now I have
return PopScope(
canPop: false,
onPopInvokedWithResult: (bool didPop, Object? result) async {
if (result == null){
final navigator = Navigator.of(context);
await _save();
navigator.pop(true);
}
},
which works, but I'm uncertain it's reliable. That is because _save() depends on fetching information from the widget tree. I also dislike how I interpret catch system pops by checking that result == null. Again, it seems unreliable. I'm also not sure if the function being async is acceptable.
Is there a straightforward, standard way to intercept pops, WHILE the widget tree is still available. Bonus Question: is there a way to intercept pushes?
(I also fot to mention that this approach messes up a feature which depends on Navigator.popUntil())
Share Improve this question edited Feb 24 at 2:18 poppy asked Feb 24 at 2:03 poppypoppy 2973 silver badges16 bronze badges1 Answer
Reset to default 1How about overriding dispose()
?
You said 'while the widget tree is still alive', but in most cases, the widget tree doesn't have to be alive. But the state should be alive since the widget tree just displays the state.
So you can use the existing state in dispose()
method.
Here's an example:
class MyWidget extends StatefulWidget {
const MyWidget({super.key});
@override
State<MyWidget> createState() => _MyWidgetState();
}
class _MyWidgetState extends State<MyWidget> {
int count = 0;
@override
void dispose() {
_save();
super.dispose();
}
Future<void> _save() async {
await Future.delayed(const Duration(seconds: 1));
print(mounted); // false, but the state is still alive
print(count);
}
@override
Widget build(BuildContext context) {
return TextButton(
onPressed: () {
setState(() {
count++;
});
},
child: Text(count.toString()),
);
}
}
For the bonus question, I'm not sure if I correctly understand, I think you can override initState()
similar to overriding dispose()
.
本文标签:
版权声明:本文标题:android - Is there a straightforward, standard way to intercept pops, WHILE the widget tree is still available? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741297169a2370885.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论