Riverpod代码生成器将Notifier状态识别为Object?而非AuthState的问题
解决Riverpod Notifier状态被识别为Object?的问题
问题根源在于未显式指定_$AuthService的泛型类型,代码生成工具无法推断正确状态类型,默认使用了Object?。按以下步骤修正:
1. 显式声明状态泛型类型
在继承_$AuthService时,通过泛型明确指定状态为AuthState,同时显式声明build()方法的返回类型:
@Riverpod(keepAlive: true) class AuthService extends _$AuthService<AuthState> { // 新增<AuthState>指定状态类型 late ApiService _apiService; late Logger _log; final _storage = const FlutterSecureStorage(); @override AuthState build() { // 明确返回AuthState类型 _apiService = ref.watch(apiServiceProvider); _log = ref.watch(loggerProvider); return AuthState(); } void testFunc() { state = state.copyWith(); // 此时state会被正确识别为AuthState,可正常调用copyWith } }
2. 重新生成代码
修改完成后,运行Riverpod代码生成命令(确保已配置build_runner):
flutter pub run build_runner build --delete-conflicting-outputs
原理说明
Riverpod代码生成工具依赖_$AuthService的泛型参数确定状态类型,若不指定,工具无法从build()返回值中准确推断,会 fallback 到Object?。显式声明泛型后,生成的auth_service.g.dart中会自动使用NotifierProvider<AuthService, AuthState>,状态类型即可正常识别。
内容的提问来源于stack exchange,提问作者Gabe
相关产品推荐
相关产品推荐

