Flutter中Navigator.pushNamed作为参数传入类后不生效问题
问题根因
你的代码存在3处核心问题导致跳转失效:
- 函数调用缺失括号:
awaitingEmailConfPage、confirmedEmailConfPage是异步函数类型变量,你仅引用了函数对象未加()执行,内部的跳转逻辑根本没有运行 - 异步方法返回值错误:
registerNewUser是异步方法,你定义返回值为void,异步执行流程无法被正确追踪,容易出现页面上下文失效问题 - 跳转逻辑写反:邮箱已验证的分支你调用了邮箱验证等待页的回调,和需求完全相反
- (附加问题)你漏写了注册核心逻辑,代码中直接取
currentUser但没有执行创建用户的操作,无法拿到刚注册的用户信息
修正后的Registration类代码
import 'package:flutter/foundation.dart'; import 'package:firebase_auth/firebase_auth.dart'; class Registration { Registration({ required this.email, required this.password, required this.awaitingEmailConfPage, required this.confirmedEmailConfPage }); // 补全构造传入的参数属性 final String email; final String password; final _auth = FirebaseAuth.instance; final Future Function() awaitingEmailConfPage; final Future Function() confirmedEmailConfPage; // 修正异步方法返回值类型 Future<void> registerNewUser() async { try { // 补全缺失的注册逻辑 await _auth.createUserWithEmailAndPassword(email: email, password: password); User? user = _auth.currentUser; if (user != null) { if (user.emailVerified) { // 加()执行回调,修正跳转逻辑 await confirmedEmailConfPage(); } else { await awaitingEmailConfPage(); } } } catch (e) { // 可按需添加异常处理逻辑 if (kDebugMode) { print('注册失败:$e'); } } } }
调用侧调整
调用异步注册方法时添加await,确保流程正常执行:
// build方法内的调用逻辑 await Registration( email: email, password: password, awaitingEmailConfPage: () async { await Navigator.pushNamed(context, EmailConfirmation.id); }, confirmedEmailConfPage: () async { await Navigator.pushNamed(context, ChatScreen.id); } ).registerNewUser();
内容的提问来源于stack exchange,提问作者Jordan Dwyer
相关产品推荐
相关产品推荐

