Flutter Web邮件跳转重置密码页:uid与token获取为空问题
问题分析与修复方案
核心问题
你的代码存在三个关键错误,导致无法正确提取uid和token:
- 路径匹配条件错误:当URL包含
uid和token时,完整路径是/reset_password/confirm/<uid>/<token>,而非/reset_password/confirm/,所以uri.path == '/reset_password/confirm/'的判断永远不成立。 - 路径段索引计算错误:
Uri.pathSegments是从0开始的数组,对于路径/reset_password/confirm/uid/token,其路径段为['reset_password', 'confirm', 'uid', 'token'],uid对应索引2,token对应索引3,并非代码中的4和5。 - 测试URL与代码路径不匹配:你注释中的测试URL是
/account/reset/OQ/...,但代码里判断的是/password_reset/confirm/,路径前缀不一致会直接导致匹配失败。
修复后的代码
Future main() async { final routeUri = html.window.location.href; final uri = Uri.parse(routeUri); String? uid; String? token; // 检查路径段数量是否足够,且前缀匹配目标路由 final pathSegments = uri.pathSegments; if (pathSegments.length >= 4 && pathSegments[0] == 'reset_password' && pathSegments[1] == 'confirm') { uid = pathSegments[2]; token = pathSegments[3]; } // 若实际使用的是测试URL的路径结构,取消下面注释并注释上面的判断 /* if (pathSegments.length >= 4 && pathSegments[0] == 'account' && pathSegments[1] == 'reset') { uid = pathSegments[2]; token = pathSegments[3]; } */ uid ??= ''; token ??= ''; print("UID - $uid TOKEN - $token"); runApp(ProviderScope(child: MyApp(uid, token))); }
额外优化建议
- 用路由框架处理参数:如果项目使用
go_router等路由框架,建议通过路由参数的方式提取uid和token,既符合Flutter Web路由规范,也能避免手动解析URL的错误。 - 兼容末尾斜杠:部分URL末尾会带
/,比如/reset_password/confirm/uid/token/,此时pathSegments会多一个空字符串,需要额外判断并调整索引。
内容的提问来源于stack exchange,提问作者Nirmal
相关产品推荐
相关产品推荐

