Flutter Bloc保持重建小部件而不改变状态

时间:2020-03-24 16:19:42

标签: android flutter dart provider bloc

学习集团模式,我对此迷迷糊糊。在第一页中,ExamBloc处理获取考试和显示内容。一旦用户选择了考试,就会调用所选考试的测验页面。 QuestionBloc提取问题并将其传递给有状态的小部件以显示问题。问题显示正确。

但是,整个页面无缘无故地不断重建。我尝试了QuizScreen小部件的有状态和无状态小部件,但仍然无法停止重建。感谢任何帮助。

´´´

 class _QuizScreenState extends State<QuizScreen> {
  @override
  Widget build(BuildContext context) {
    final QuestionBloc questionBloc = context.bloc<QuestionBloc>();
    questionBloc.add(FetchQuestion(widget.selectedExam));

    return
       BlocBuilder<QuestionBloc,QuestionState>(
         bloc: questionBloc,
         builder: (context, state) {
           print('entrance'+state.toString());
           if (state is QuestionIsLoading)
             return Center(child: CircularProgressIndicator());
           if (state is QuestionIsLoaded){
            final QuizBrain quizBrain =QuizBrain(state.questionList);
            List<QuestionModel> ql=state.questionList;
             return Scaffold(
                 body:  Choices(quizBrain: quizBrain, questionList: ql));}
         },
       );
  }
}


class Choices extends StatefulWidget {

 Choices({@required this.quizBrain,@required this.questionList});
 final List<QuestionModel> questionList;
 final QuizBrain quizBrain;
  @override
  _ChoicesState createState() => _ChoicesState();
}

class _ChoicesState extends State<Choices> {
  var _selection;

  onChangedRB(String  value) { setState(() { _selection = value; });
  print('onchange clicked');
  print(value);
  widget.quizBrain.nextQuestion();
  }
  @override
  Widget build(BuildContext context) {
    return  Column(
      mainAxisAlignment: MainAxisAlignment.center,
      crossAxisAlignment: CrossAxisAlignment.stretch,
      children: <Widget>[

        Text(
          widget.quizBrain.getNextQuestion().content,
          textAlign: TextAlign.center,
          overflow: TextOverflow.ellipsis,
          style: TextStyle(fontWeight: FontWeight.bold),
        ),
        Container(child: RB(choice:widget.quizBrain.getNextQuestion().content,value:'A',groupValue:_selection,onChanged:onChangedRB
        )),


      ],
    );

  }
}

´´´

1 个答案:

答案 0 :(得分:2)

您正在无限循环:

在构建器中,您正在添加新事件。解析事件后,它会添加状态并将此状态传递给构建器:

BlocBuilder 正在侦听 QuestionBloc 状态更改。使用 BlocProvider 您将添加事件,这会向 BlocBuilder 添加新状态。

长话短说,您不应添加相同类型的Bloc事件

BlocProvider.of<QuestionBloc>(context).add(FetchQuestion(widget.selectedExam))

在同一Bloc构建器(BlocBuilder<QuestionBloc,QuestionState>)中。