如何获得Bloc的最新更新状态



我有一个关于最新更新的区块状态的问题。我有一个带有onPressed功能的按钮:

  1. 首先我触发一个事件,它会改变状态
  2. 在我检索状态之后,它的值不会立即更新为最新的事件。要检索状态,我使用BlocBuilder中的state或上下文BlocProvider.of(context(.state中的state,但什么都不起作用

您对如何检索最新的状态版本有什么想法吗?谢谢下面的代码:

class InputWidget extends StatefulWidget {
const InputWidget({Key? key}) : super(key: key);
@override
State<InputWidget> createState() => _InputWidgetState();
}
class _InputWidgetState extends State<InputWidget> {
late TextEditingController amountController;
String? categoryValue;
String? typeValue;
@override
void initState() {
super.initState();
amountController = TextEditingController();
}
@override
void dispose() {
amountController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return BlocBuilder<QuizBloc, QuizState>(
builder: (context, state) {
return Form(
child: Column(
children: [
ElevatedButton(
onPressed: () {
BlocProvider.of<QuizBloc>(context).add(
const QuizEvent.getQuizPressed(),
);
// Here i retrieve the state, the aim is to navigate to another page if 
//state is...
if (BlocProvider.of<QuizBloc>(context).state.value || state.value) {
context.router.push(const QuizRoute());}
},
child: const Text(
'Start the quiz',
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 20,
color: Colors.white,
),
),
),
],
),
);
},
);
}
}

您没有显示区块代码。但我的猜测是,您发送的是具有更新值的相同状态。这是行不通的(有一种方法,但那不是典型的逻辑(。您需要先发送另一个状态。

因此,让我们假设你有一个状态",然后你发送事件",选择"-在块内,这个事件的逻辑首先会产生事件"inProgress",最后是逻辑,最后你再次产生"expectInput">

我通过使用BLocListener((解决了这个问题,该函数允许我在状态值为true时导航到新页面。它似乎在起作用,因为它给了我最新的状态。

最新更新