【发布时间】:2021-01-21 16:16:07
【问题描述】:
在下面的例子中,我们可以看到块是在这个有状态的小部件中新创建的
authenticationBloc = AuthenticationBloc(userRepository: userRepository);
class App extends StatefulWidget {
final UserRepository userRepository;
App({Key key, @required this.userRepository}) : super(key: key);
@override
State<App> createState() => _AppState();
}
class _AppState extends State<App> {
AuthenticationBloc authenticationBloc;
UserRepository get userRepository => widget.userRepository;
@override
void initState() {
authenticationBloc = AuthenticationBloc(userRepository: userRepository); <------
authenticationBloc.dispatch(AppStarted());
super.initState();
}
@override
void dispose() { <---------
authenticationBloc.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return BlocProvider<AuthenticationBloc>(
bloc: authenticationBloc,
child: MaterialApp(
home: BlocBuilder<AuthenticationEvent, AuthenticationState>(
bloc: authenticationBloc,
builder: (BuildContext context, AuthenticationState state) {
if (state is AuthenticationUninitialized) {
return SplashPage();
}
if (state is AuthenticationAuthenticated) {
return HomePage();
}
if (state is AuthenticationUnauthenticated) {
return LoginPage(userRepository: userRepository);
}
if (state is AuthenticationLoading) {
return LoadingIndicator();
}
},
),
),
);
}
}
但是它也被放置在同一个有状态的小部件中
@override
void dispose() {
authenticationBloc.dispose(); <-----
super.dispose();
}
现在在子小部件HomePage() 中,如果authenticationBloc 已经在App statefulwidget 中处理,我怎么还能使用BlocProvider.of<AuthenticationBloc>(context) 访问它?
authenticationBloc.dispose(); 不是正在关闭水槽吗?还是我理解错了?
【问题讨论】:
标签: flutter dart flutter-bloc