【发布时间】:2022-01-09 17:23:55
【问题描述】:
我想从cubit更改bool值,但我不知道该怎么做。
我想要实现的是,例如:if (boolean value stored in cubit is true) "show widget A" : "show widget B"
我的代码:
class ChangeBoolCubit extends Cubit<bool> {
ChangeBoolCubit() : super(false);
bool one = false;
bool two = true;
void changeValue(bool booleanToChange) {
booleanToChange = !state;
emit(booleanToChange);
}
}
查看:
class BoolView extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Changing Bool')),
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Center(
child: BlocBuilder<ChangeBoolCubit, bool>(
builder: (context, state) {
return (ChangeBoolCubit().one)
? Text('TRUE: ${ChangeBoolCubit().one}')
: Text('FALSE: ${ChangeBoolCubit().one};');
},
),
),
Center(
child: BlocBuilder<ChangeBoolCubit, bool>(
builder: (context, state) {
return (ChangeBoolCubit().two)
? Text('TRUE: ${ChangeBoolCubit().two}')
: Text('FALSE: ${ChangeBoolCubit().two};');
},
),
),
],),
floatingActionButton: Column(
mainAxisAlignment: MainAxisAlignment.end,
crossAxisAlignment: CrossAxisAlignment.end,
children: <Widget>[
FloatingActionButton(
child: const Icon(Icons.add),
onPressed: () => context.read<ChangeBoolCubit>().changeValue(ChangeBoolCubit().one),
),
const SizedBox(height: 8),
FloatingActionButton(
child: const Icon(Icons.remove),
onPressed: () => context.read<ChangeBoolCubit>().changeValue(ChangeBoolCubit().two),
),
],
),
);
}
}
对于这个微不足道的问题,我很抱歉,但我是 Cubit/Bloc 的新手。
【问题讨论】:
标签: flutter bloc flutter-state cubit flutter-cubit