我正试图使用Riverpod中的ProviderListener来监听我的authProvider,并控制用户是否获得授权时显示的页面。我得到错误:
错误:参数类型"StateNotificationProvider<Auth,bool>'无法分配给参数类型"ProviderBase<对象,StateController>'。
错误显示在ProviderListener 内的:provider:authProvider上
我想知道这是否是由于StateNotificationProvider的更新?
我想知道如何更好地使用ProviderListener,即使有更好的方法来处理授权流程(我对反馈和批评持开放态度,非常感谢任何人能提供帮助(。我删掉了不相关的代码
import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
class Auth extends StateNotifier<bool> {
Auth() : super(false);
void setAuth(bool auth) {
state = auth;
}
}
final authProvider = StateNotifierProvider<Auth, bool>((ref) => Auth());
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
runApp(
ProviderScope(
child: MyApp(),
),
);
}
class MyApp extends StatefulHookWidget {
// const MyApp({Key key}) : super(key: key);
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
final Future<FirebaseApp> _fbMyApp = Firebase.initializeApp();
Widget route = SplashScreen();
@override
Widget build(BuildContext context) {
return ProviderListener<StateController<bool>>(
provider: authProvider,
onChange: (context, auth) {
if (auth.state = true) {
route = HomeScreen();
} else {
route = SplashScreen();
}
},
child: MaterialApp(
home: route,
);
}
}
我设法将其更改为:
return ProviderListener<StateNotifier<bool>>(
provider: authProvider.notifier,
它给了我一个非突破性的错误:信息:成员"state"只能在"package:state_notifier/state_notifier.dart"的子类的实例成员中使用。(invalid_use_of_protected_member(
并且工作不正常-当我使用上下文时,状态没有更新。读取
context.read(authProvider.notifier).state = true;
所以它有童车,但没有完全坏掉。至少这是一个进步。我仍然希望得到任何人的帮助和反馈!
从ProviderListener
中删除StateController
,只保留类型(在本例中为bool(
return ProviderListener<bool>(
provider: authProvider, //this will read the state of your provider (a bool state)
onChange: (context, auth) {
if (auth) { //remove setter auth = true, it doesn't make sense to set a value inside an if
route = HomeScreen();
} else {
route = SplashScreen();
}
},
child: MaterialApp(
home: route,
);
通过这种方式,您可以读取StateNotifier
的状态