BLoC:多次侦听回调

时间:2019-06-09 23:27:38

标签: flutter dart bloc rxdart

我有一个有状态的小部件,该小部件从其父级获取一个块:

class Page extends StatefulWidget {
  @override
  State<StatefulWidget> createState() =>
  _PageState();
}

class _PageState extends State<Page> {
  final TextEditingController mnemonicController = TextEditingController();
  final _scaffoldKey = GlobalKey<ScaffoldState>();

  @override
  Widget build(BuildContext context) {

final MnemonicLogicBloc mnemonicLogicBloc =
BlocProvider.of<MnemonicLogicBloc>(context);

mnemonicLogicBloc.outCheckMnemonic.listen((isCorrect){
  if (!isCorrect) {
    SnackBar copySnack = SnackBar(content: Text('Wrong Mnemonic!'));
    _scaffoldKey.currentState.showSnackBar(copySnack);
  }
});

return Scaffold(
    key: _scaffoldKey,
    body: Container(
      width: double.infinity,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: <Widget>[
          Container(
            child: TextField(
              controller: mnemonicController,
            ),
          ),
          RaisedButton(
            onPressed: () {
              mnemonicLogicBloc.isMnemonicCorrect(mnemonicController.text);
            },
            child: Text('Check', style: TextStyle(color: Colors.white)),
          )
        ],
      ),
    ));
}
}

我要检查的是,当用户按下按钮时,是否插入正确的字符串。我在bloc中调用的方法是:

void isMnemonicCorrect(String typedMnemonic){
if(typedMnemonic == _lastGeneratedMnemonic)
  _inCheckMnemonic.add(true);
else
  _inCheckMnemonic.add(false);
 }

_inCheckMnemonic是我的主题的接收器(我正在使用rxDart),而outCheckMnemonic是我的Stream。问题是,即使一次调用了块的'isCorrect'方法,该监听回调也被调用了两次(SnackBar被显示了两次)。为什么会这样?

编辑:我仅使用Navigator.push导航到Page():

Navigator.of(context).push(MaterialPageRoute(
                            builder: (BuildContext context) {
                return Page();
}));

我能够检索该bloc,因为在我的应用启动时,我初始化了bloc:

return runApp(BlocProvider<ApplicationBloc>(
bloc: ApplicationBloc(),
child: BlocProvider<MnemonicLogicBloc>(
  bloc: MnemonicLogicBloc(),
  child: BlocProvider<HomePageBloc>(
    bloc: HomePageBloc(),
    child: App(),
  ),
)

));

1 个答案:

答案 0 :(得分:2)

Widget中添加新的Navigator时,请避免在构建器内部创建该小部件,而应在外部声明变量并在构建器中重新使用该变量,如下所示:

final page = Page();
Navigator.of(context).push(MaterialPageRoute(
                            builder: (BuildContext context) => page ), );

通过此更改,我们避免了以意外方式多次重新创建窗口小部件。