使用块的用户授权问题。
Widget build(BuildContext context) {
return MaterialApp(
home: MultiBlocProvider(
providers: [
BlocProvider(
create: (context) => AuthBloc(authServiceTest: authServiceTest)
..add(AppStartedEvent()),
),
],
child: BlocBuilder<AuthBloc, AuthState>(builder: (context, state) {
if (state is Authenticated) {
return app(state.user);
} else if (state is UnAuthenticated) {
return HomeScreenTest();
} else {
return Container();
}
}),
),
),
);
}
Widget app(FirebaseUser user) {
return Center(
child: Text('hello'),
);
}
}
堵塞
class AuthBloc extends Bloc<AuthEvent, AuthState> {
AuthServiceTest authServiceTest;
AuthBloc({@required AuthServiceTest authServiceTest}) {
this.authServiceTest = authServiceTest;
}
@override
AuthState get initialState => AuthInitial();
@override
Stream<AuthState> mapEventToState(AuthEvent event) async* {
if (event is AppStartedEvent) {
try {
var isSignedin = await authServiceTest.isSignedIn();
if (isSignedin) {
var user = await authServiceTest.currentUser();
yield Authenticated(user: user);
} else {
yield UnAuthenticated();
}
} catch (e) {
yield UnAuthenticated();
}
}
}
}
阻止事件
class AppStartedEvent extends AuthEvent {
@override
List<Object> get props => throw UnimplementedError();
}
阻塞状态
class Authenticated extends AuthState {
final FirebaseUser user;
Authenticated({@required this.user});
@override
List<Object> get props => [];
}
class UnAuthenticated extends AuthState {
@override
List<Object> get props => throw UnimplementedError();
所有功能
class AuthServiceTest {
FirebaseAuth auth = FirebaseAuth.instance;
Future registerUser(String email, String password) async {
var authResult = await auth.createUserWithEmailAndPassword(
email: email, password: password);
return authResult.user;
}
Future signIn(email, password) async {
var authResult = await auth.signInWithEmailAndPassword(
email: email,
password: password,
);
return authResult.user;
}
Future signOut() async {
await auth.signOut();
}
Future<bool> isSignedIn() async {
var currentUser = await auth.currentUser();
return currentUser != null;
}
Future currentUser() async {
var user = await FirebaseAuth.instance.currentUser();
return user;
}
}
授权工作,在它应该显示应用程序小部件之后,但它没有。或者逻辑或功能块中的问题,我没有正确注册以获取用户。
凭记忆写的,可能需要在某个地方更正。该方法
isSignedIn()
可以删除。如果控制台中没有显示任何内容,那么这就是问题所在
if (event is AppStartedEvent)
。您的用户如何获得授权?如果通过调用,
AuthServiceTest.signIn(email, password)
那么您的 BloC 无法跟踪这些更改,您需要向 Bloc 添加两个附加事件:SignIn 和 SignOut,块内将调用相应的方法AuthServiceTest
它看起来像这样:
事态发展
阻止自己:
之后调用
authBloc.add(SignInEvent(email, password))
会authBloc.add(SignOutEvent())
导致block状态的相应变化和UI的重绘,最终会在授权时显示你的app widget