当用户导航到新页面时,我为自定义构建按钮添加了涟漪效果。对于按钮内部的显示波纹效应,我将用户导航到新页面的时间延迟了150毫秒,如下面的代码片段所示。
onTap: () {
Future.delayed(const Duration(milliseconds: 150), () {
context.push("/SampleNextPage");
});
},
定义路线
go_router 5.0.5
class Routes {
final router = GoRouter(
// initialLocation: "HomeTitlesPage",
routes: [
GoRoute(
path: "/",
builder: (context, state) => const SplashScreen(),
),
GoRoute(
path: "/HomePage",
builder: (context, state) => const HomePage(),
),
GoRoute(
path: "/SampleNextPage",
builder: (context, state) => const SampleNextPage(),
),
], observers: [
GoRouterObserver(),
]);
}
GoRouterObserver
class GoRouterObserver extends NavigatorObserver {
@override
void didPush(Route<dynamic> route, Route<dynamic>? previousRoute) {
print('Pushed route: ${route.str}'); //name comes back null
if (previousRoute != null) {
print('previousRoute: ${previousRoute.str}');
}
}
@override
void didPop(Route<dynamic> route, Route<dynamic>? previousRoute) {
print('Poped route: ${route.str}'); //name comes back null
if (previousRoute != null) {
print('previousRoute: ${previousRoute.str}');
}
}
@override
void didRemove(Route<dynamic> route, Route<dynamic>? previousRoute) {
print('Removed route: ${route.str}'); //name comes back null
if (previousRoute != null) {
print('previousRoute: ${previousRoute.str}');
}
}
@override
void didReplace({Route<dynamic>? newRoute, Route<dynamic>? oldRoute}) {
print('Replaced newRoute: ${newRoute!.str}');
print('oldRoute: ${oldRoute!.str}'); //n//name comes back null
}
}
extension on Route<dynamic> {
String get str => 'route(${settings.name}: ${settings.arguments})';
}
同时,如果用户单击导航按钮两次,则页面会被推到路线树两次。
因此,我需要预览波纹效果,并防止两次推送同一页面。
有办法做到这一点吗?
您可以在用户点击一次按钮后使其处于非活动状态吗?这将使他们无法再次点击它!。。。像这样:
bool activeButton = true;
onTap: activeButton
? () {
// This requires a StatefulWidget:
setState(() {
activeButton = false;
});
Future.delayed(const Duration(milliseconds: 150), () {
context.push("/SampleNextPage");
});
}
: null
否则(例如,如果出于某种原因,您希望按钮保持活动和可点击状态,但仍然不能按下多个SampleNextPage(,您可以在按下之前编写一个条件。我不知道你的GoRouterObserver是如何工作的,但有这样的东西:
onTap: (){
Future.delayed(const Duration(milliseconds: 150), () {
if (GoRouterObserver().topRoute.path != "/SampleNextPage") {
context.push("/SampleNextPage");
}
});
}
编辑
好吧,我不理解你的GoRouterObserver!在我看来,它似乎没有观察到任何东西…
当我处于类似的情况时,我会使用NavigationHistoryObserver!像这样:
import 'package:navigation_history_observer/navigation_history_observer.dart';
onTap: (){
Future.delayed(const Duration(milliseconds: 150), () {
if (NavigationHistoryObserver().top!.settings.name != "/SampleNextPage") {
context.push("/SampleNextPage");
}
});
}