我在螢屏上有兩個小部件,一個加載小部件和一個按鈕小部件,我想在每次點擊按鈕時更改加載小部件的狀態。
加載小部件
class LoadingWidget extends StatelessWidget {
const LoadingWidget({
Key? key,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return BlocBuilder<LoadingCubit, bool>(
bloc: BlocProvider.of<LoadingCubit>(context),
builder: (context, loadingState) {
return Center(
child: Visibility(
visible: BlocProvider.of<LoadingCubit>(context).state,
child: const CircularProgressIndicator(
backgroundColor: Color(0xFF2C2C2C),
)),
);
});
}
}
裝載肘
class LoadingCubit extends Cubit<bool> {
LoadingCubit() : super(true);
toggleLoading() {
emit(!state);
}
}
加載按鈕
class AutoLoginButton extends StatelessWidget {
const AutoLoginButton({
Key? key,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return BlocBuilder<AutoLoginCubit, bool>(
bloc: BlocProvider.of<AutoLoginCubit>(context),
builder: (context, autoLoginState) => InkWell(
child: Row(
children: [
Icon(
autoLoginState == false
? Icons.check_box_outline_blank
: Icons.check_box,
),
],
),
onTap: () {
BlocProvider.of<AutoLoginCubit>(context).toggleAutoLogin();
},
),
);
}
}
鈕肘
class AutoLoginCubit extends Cubit<bool> {
AutoLoginCubit() : super(false){
initState().then((value) => emit(value));
}
void toggleAutoLogin() async {
if (state == false) {
emit(true);
} else {
emit(false);
}
AutoLoginService().setAutoLoginState(state: state);
}
Future<bool> initState() async{
return await AutoLoginService().getAutoLoginState();
}
}
這頁紙
Row(
children:[
BlocProvider(
create: (context) => AutoLoginCubit(),
child: const AutoLoginButton(),
),
BlocProvider(
create: (BuildContext context) => LoadingCubit(),
child: const LoadingWidget()),
]
)
uj5u.com熱心網友回復:
您應該使用
要使其可見,Cubit muts 必須在 heiarchy 中上移:

uj5u.com熱心網友回復:
您需要在 AutoLoginButton onTap 函式上切換加載BlocProvider.of<LoadingCubit>(context).toggleLoading();以觸發加載小部件的重建,但要能夠呼叫您需要toggleLoading()在. 所以我的解決方案是:LoadingCubitAutoLoginButton
MultiBlocProvider(
providers: [
BlocProvider(create: (context) => AutoLoginCubit()),
BlocProvider(create: (BuildContext context) => LoadingCubit()),
],
child: Row(
children: [
const AutoLoginButton(),
const LoadingWidget(),
],
),
),
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/434605.html
