Flutter - cubit - 改变cubit内的布尔值
Posted
技术标签:
【中文标题】Flutter - cubit - 改变cubit内的布尔值【英文标题】:Flutter - cubit - changing boolean value inside cubit 【发布时间】: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 的新手。
【问题讨论】:
【参考方案1】:您应该使用 BlocBuilder 中的状态。
例如:
BlocBuilder<ChangeBoolCubit, bool>(
builder: (context, state)
return state
? Text('TRUE: $ChangeBoolCubit().one')
: Text('FALSE: $ChangeBoolCubit().one;');
,
)
但是,我认为这就是你想要的:
class ChangeBoolState
final bool one;
final bool two;
ChangeBoolState(this.one = false, this.two = true);
ChangeBoolState copyWith(
bool? one,
bool? two,
)
return RegisterState(
one: one != null ? one : this.one,
two: two != null ? two : this.two
);
class ChangeBoolCubit extends Cubit<ChangeBoolState>
void changeOne()
emit(state.copyWith(
one: !state.one,
));
然后像这样使用它:
BlocBuilder<ChangeBoolCubit, bool>(
builder: (context, state)
return state.one
? Text('TRUE: $state.one')
: Text('FALSE: $state.two;');
,
)
【讨论】:
以上是关于Flutter - cubit - 改变cubit内的布尔值的主要内容,如果未能解决你的问题,请参考以下文章
在 Flutter 中使用 Bloc/Cubit 时绕过 CONTEXT