Flutter:如何在Beamer Guard的check方法中使用Future并解决非空返回错误
问题解决思路
首先明确错误根源:BeamGuard的check方法要求同步返回一个非空的bool值,但你在里面写了异步的存储读取操作,而且当前代码里的check函数根本没有返回任何值,自然触发非空错误。另外,check是同步方法,没法直接处理异步逻辑,不能在里面用Future。
正确的做法是把异步读取存储、初始化认证状态的逻辑提前到App启动阶段,而非放在路由守卫里执行。具体步骤如下:
1. 在AuthenticationNotifier中提前加载认证状态
给AuthenticationNotifier新增一个初始化方法,在App启动时调用它,提前读取FlutterSecureStorage里的userId并设置认证状态:
class AuthenticationNotifier extends ChangeNotifier { bool _isAuthenticated = false; bool get isAuthenticated => _isAuthenticated; // 新增初始化认证状态的方法 Future<void> initAuthStatus() async { const storage = FlutterSecureStorage(); final userId = await storage.read(key: "userId"); if (userId != null) { _isAuthenticated = true; notifyListeners(); } } void setUserAuth(bool status) { _isAuthenticated = status; notifyListeners(); } }
然后在App启动流程中调用这个初始化方法,比如在main函数里:
void main() async { WidgetsFlutterBinding.ensureInitialized(); final authNotifier = AuthenticationNotifier(); await authNotifier.initAuthStatus(); // 提前加载认证状态 runApp( ChangeNotifierProvider.value( value: authNotifier, child: MyApp(), ), ); }
2. 修改BeamGuard的check方法
现在认证状态已经提前初始化完成,check方法只需要同步判断isAuthenticated的值即可,不需要任何异步操作:
final _routerDelegate = BeamerDelegate( updateListenable: authNotifier, guards: [ BeamGuard( beamToNamed: (origin, target) => '/$locationAuth', pathPatterns: [ ...HomeLocation().pathPatterns, ], check: (context, location) { final loginNotifier = Provider.of<AuthenticationNotifier>(context, listen: false); // 直接返回同步的认证状态值 return loginNotifier.isAuthenticated; }, ), ], locationBuilder: BeamerLocationBuilder(beamLocations: [ HomeLocation(), AuthLocation(), ]), );
原代码问题说明
check是同步回调,要求立即返回bool,无法处理异步逻辑,你里面的_getUserId()是异步方法,没法在同步函数里等待它执行完成。- 当前的
check函数没有返回任何值,既不符合返回bool的要求,也没有返回Future,完全不匹配方法签名,所以编译器抛出非空错误。
内容的提问来源于stack exchange,提问作者broheat
相关产品推荐
相关产品推荐

