我有一个没有任何Bloc的Landing UI,一个带有Bloc的Register UI、一个带有Bloc的Verification UI和一个带有Blob的Home UI。在每一个中,我都定义了BlocProvider.of。在我在Home of Material应用程序中定义的主要内容中,多个Bloc提供商每个都有自己的子级,提供商的主要子级是这样的登录页:
home: MultiBlocProvider(
providers: [
BlocProvider<UserBloc>(
create: (context) => UserBloc(UsRepoImp()),
child: RegisterUi(),
),
BlocProvider<VerificationBloc>(
create: (context) => VerificationBloc(VerRepoImp()),
child: VerificationUi(),
),
BlocProvider<HomeBloc>(
create: (context) => HomeBloc(HomeRepoImp()),
child: HomeUi(),
),
],
child: LandingUi(),
),
还有一件事,Verification UI从Register Bloc状态返回,如下所示:
BlocBuilder<UserBloc, UserState>(
builder: (context, state) {
if (state is UserLoading) {
return CircularProgressIndicator(
valueColor:
AlwaysStoppedAnimation<Color>(Color(0xff7b68ee)),
);
} else if (state is UserRegistered) {
return VerifyAccount();
} else if (state is UserError) {
return Text('Error');
}
return SizedBox(
height: 10.0,
);
},
),
但当我运行时,我有一个错误,即Blob不应该有祖先我应该如何使这些Blob与UI更改正确通信
我认为您使用MultiBlocProvider
的方式不对。您不应该在那里提供child
,而应该在那里只提供create
函数的参数,然后在该MultiBlocProvider
下面的小部件树中,您可以使用BlocBuilder
来侦听树中上面提供的任何bloc,如果您需要在同一小部件中侦听多个bloc,则需要嵌套BlocBuilder
s。
示例:
@override
Widget build(BuildContext context) => MultiBlocProvider(
providers: [
BlocProvider<RecorderBloc>(
create: (context) => myFirstBloc(),
),
BlocProvider<PermissionBloc>(
create: (context) => mySecondBloc(),
)
],
child:myChild()
);
然后进入my_child.dart:
@override
Widget build(BuildContext context) {
return BlocBuilder<MyFirstBloc, MyFirstBlocState>(
builder: (context, myFirstBlocState) =>
BlocBuilder<MySecondBloc, MySecondBlocState>(
builder: (context, secondBlocState) {
//return widget based on the states of both blocs...
},
),
);
}