如何在go_router中配置斜杠分隔的可变路径参数获取嵌套插件UUID列表?
在GoRouter中支持嵌套插件的UUID路径并获取有序UUID列表
路由修改方案
将原路由/plugin/:uuid修改为/plugin/:pluginPath*,其中*是GoRouter的通配符参数,用于匹配/plugin/之后的所有路径片段(无论嵌套层级多少)。
实现代码示例
1. GoRouter配置
final GoRouter router = GoRouter( routes: <RouteBase>[ // 其他路由配置... GoRoute( path: '/plugin/:pluginPath*', builder: (BuildContext context, GoRouterState state) { // 从路由状态中获取捕获的路径字符串 final String? rawPath = state.pathParameters['pluginPath']; // 拆分路径为有序UUID列表:按/分割,过滤空字符串(避免路径末尾/导致的空元素) final List<String> uuidChain = rawPath?.split('/').where((str) => str.isNotEmpty).toList() ?? []; // 将UUID列表传递给插件页面 return PluginHostPage(uuidChain: uuidChain); }, ), ], );
2. 插件页面接收UUID列表
class PluginHostPage extends StatelessWidget { final List<String> uuidChain; const PluginHostPage({super.key, required this.uuidChain}); @override Widget build(BuildContext context) { // 根据UUID链的层级渲染对应插件: // uuidChain[0] = 顶级插件UUID // uuidChain[1] = 子插件UUID(如果存在) // uuidChain[2] = 孙插件UUID(如果存在) return Scaffold( appBar: AppBar(title: Text('插件层级:${uuidChain.length}')), body: Padding( padding: const EdgeInsets.all(16.0), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ const Text('当前插件UUID链:', style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold)), ...uuidChain.map((uuid) => Padding( padding: const EdgeInsets.symmetric(vertical: 4.0), child: Text(uuid), )), ], ), ), ); } }
关键说明
- 路由匹配逻辑:
/:pluginPath*会捕获/plugin/之后的所有内容,比如访问/plugin/uuid1/uuid2/uuid3时,pluginPath的值为uuid1/uuid2/uuid3 - UUID列表顺序:拆分后的列表严格遵循URL中UUID的顺序,第一个元素是最外层插件的UUID,后续元素依次为嵌套的子插件、孙插件UUID
- 边界处理:通过
where((str) => str.isNotEmpty)过滤空字符串,避免因路径末尾多一个/(如/plugin/uuid1/)导致列表出现无效空元素
内容的提问来源于stack exchange,提问作者hacker1024
相关产品推荐
相关产品推荐

