使用Go Router通用路由时如何传递页面路径参数?
两种实现方法解决你的问题
方法一:直接提取指定参数(适合固定路径结构)
如果你的路径固定是factfile/[字符名],可以把路由路径改成带命名参数的形式,直接拿到MickeyMouse这类字符串:
final router = GoRouter( routes: [ GoRoute( path: '/', builder: (_, __) => Scaffold( appBar: AppBar(title: const Text('Home Screen')), ), routes: [ GoRoute( path: 'factfile/:character', // 用:character定义命名参数 builder: (context, state) => ShowFactfile( characterName: state.params['character']!, // 直接取参数值 ), ), ], ), ], );
当访问www.mywebsite.com/factfile/MickeyMouse时,state.params['character']就会返回MickeyMouse,直接传给ShowFactfile类即可。实际项目里建议加非空判断,比如state.params['character'] ?? '默认值',避免空指针异常。
方法二:获取完整路径或通配符部分(适合可变路径结构)
如果路径可能有更多层级(比如factfile/MickeyMouse/detail),或者你需要完整路径,可以保留通配符*,通过以下两种方式获取:
方式1:获取通配符匹配的部分
final router = GoRouter( routes: [ GoRoute( path: '/', builder: (_, __) => Scaffold( appBar: AppBar(title: const Text('Home Screen')), ), routes: [ GoRoute( path: 'factfile/*', builder: (context, state) { // 获取通配符匹配的部分,比如MickeyMouse或者MickeyMouse/detail final wildcardPath = state.params['*']!; // 若只需要斜杠后的第一个部分,分割字符串即可 final characterName = wildcardPath.split('/').first; return ShowFactfile(path: wildcardPath, characterName: characterName); }, ), ], ), ], );
方式2:获取完整页面路径
如果需要整个URL的路径部分,可以用context.location:
final router = GoRouter( routes: [ GoRoute( path: '/', builder: (_, __) => Scaffold( appBar: AppBar(title: const Text('Home Screen')), ), routes: [ GoRoute( path: 'factfile/*', builder: (context, state) { // 获取完整路径,比如/factfile/MickeyMouse final fullPath = context.location; // 提取斜杠后的目标部分,比如MickeyMouse final characterName = fullPath.split('/').skip(2).first; return ShowFactfile(fullPath: fullPath, characterName: characterName); }, ), ], ), ], );
内容的提问来源于stack exchange,提问作者Nibbles
相关产品推荐
相关产品推荐

