Flutter条件登录中navigator.pushReplacementNamed无法跳转页面
Flutter条件登录跳转失效问题解决
你的switch语句没触发跳转,核心原因是**result.model.toString()的返回值不是你预期的"PetOwnerModel"或"VeterinarianModel"**。Dart中对象默认的toString()方法输出是Instance of '类名'格式,比如Instance of 'PetOwnerModel',和你写的字符串完全不匹配,自然走不到对应的分支。
推荐解决方法:直接判断模型类型(最安全可靠)
不用依赖字符串匹配,直接用is关键字判断对象类型,代码更简洁且不易出错:
修改登录按钮的逻辑代码:
onPressed: loginController.isButtonEnabled ? () async { final navigator = Navigator.of(context); showDialog( context: context, builder: (context) => const Center(child: CircularProgressIndicator()), ); final result = await loginController.signIn( _emailController.text, _passwordController.text, ); if (result.model != null) { debugPrint(result.model.toString()); // 直接判断模型类型,替代switch字符串匹配 if (result.model is PetOwnerModel) { navigator.pushReplacementNamed(homeRoute); } else if (result.model is VeterinarianModel) { navigator.pushReplacementNamed(vetHomeRoute); } } else { showDialog( context: context, builder: (context) => AlertDialog( title: const Text("Error"), content: Text(result.errorMessage!), actions: <Widget>[ TextButton( child: const Text('OK'), onPressed: () { navigator.pop(); }, ) ], ), ); } } : null,
其他可选方案
方案1:重写模型类的toString方法
如果坚持要用字符串匹配,可以在PetOwnerModel和VeterinarianModel中重写toString()方法,返回纯类名:
class PetOwnerModel { // ... 其他代码 @override String toString() => "PetOwnerModel"; } class VeterinarianModel { // ... 其他代码 @override String toString() => "VeterinarianModel"; }
这样result.model.toString()就会返回你预期的字符串,switch分支就能正常触发。
方案2:在ApiResponse中携带用户类型标识
可以在ApiResponse的子类中添加UserType字段,后续直接通过这个字段判断跳转,不用依赖模型类型:
比如修改ApiPetOwnerResponse和ApiVeterinarianResponse:
class ApiPetOwnerResponse extends ApiResponse { final PetOwnerModel? model; final UserType userType = UserType.owner; // 添加类型标识 // ... 构造函数等代码 } class ApiVeterinarianResponse extends ApiResponse { final VeterinarianModel? model; final UserType userType = UserType.veterinarian; // 添加类型标识 // ... 构造函数等代码 }
然后登录逻辑中可以这样判断:
if (result is ApiPetOwnerResponse) { navigator.pushReplacementNamed(homeRoute); } else if (result is ApiVeterinarianResponse) { navigator.pushReplacementNamed(vetHomeRoute); }
内容的提问来源于stack exchange,提问作者Felix A. Covarrubias Perez
相关产品推荐
相关产品推荐

