gpt4 book ai didi

dart - 当小部件被路由到/离开时的类回调函数

转载 作者:IT王子 更新时间:2023-10-29 06:40:30 24 4
gpt4 key购买 nike

我正在寻找一种在我的小部件类中具有某种回调函数的方法。本质上,我正在寻找这样的东西:

class SomeWidget extends StatefulWidget with RouteHandlerMixin {
// ...

void onRouteTo(Route oldRoute) {
// Do stuff before this widget gets routed to
// Perhaps return a bool to approve/cancel the route
}

void onRouteAway(Route newRoute) {
// Do stuff before this widget gets routed away from
// Perhaps return a bool to approve/cancel the route
}

// ...
}

Flutter 是否支持这种行为?我能找到/想到的最接近的是一些简陋的解决方案,涉及将逻辑放在根 MaterialApponGenerateRoute 属性中。

最佳答案

你要找的是RouteAware

// Register the RouteObserver as a navigation observer.
final RouteObserver<PageRoute> routeObserver = RouteObserver<PageRoute>();
void main() {
runApp(MaterialApp(
home: Container(),
navigatorObservers: [routeObserver],
));
}

class RouteAwareWidget extends StatefulWidget {
State<RouteAwareWidget> createState() => RouteAwareWidgetState();
}

// Implement RouteAware in a widget's state and subscribe it to the RouteObserver.
class RouteAwareWidgetState extends State<RouteAwareWidget> with RouteAware {

@override
void didChangeDependencies() {
super.didChangeDependencies();
routeObserver.subscribe(this, ModalRoute.of(context));
}

@override
void dispose() {
routeObserver.unsubscribe(this);
super.dispose();
}

@override
void didPush() {
// Route was pushed onto navigator and is now topmost route.
}

@override
void didPopNext() {
// Covering route was popped off the navigator.
}

@override
Widget build(BuildContext context) => Container();

}

关于dart - 当小部件被路由到/离开时的类回调函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53089847/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com