首页 > 解决方案 > Flutter mobx 观察者不在 List.firstWhere 上工作

问题描述

嗨,我想更新我的模型列表。

我的模型;

class Question {
    String id;
    String title;
    String questionInfo;
    String questionInfoSub;
    List<Answers> answers;
}

我的观点;

 ListView buildListView(ServiceStore _serviceStore, context) {
        return ListView.builder(
            itemCount: _serviceStore.answersSummaryList.length,
            itemBuilder: (context, index) {
              return Observer(builder: (context) {
                return ReadOnlyWidget(
                  question: _serviceStore.answersSummaryList[index],
                  editIcon: true,
                  onPress: () {
                    showModalBottomSheetSummary(
                        context, _serviceStore.answersSummaryList[index]);
                  },
                );
              });
            });
      }

我正在使用操作函数更新 showModalBottomSheetSummary 中的对象;

'''

 @observable
  ObservableList<Question> _answersSummaryList = new ObservableList();

@action
  updateAnswer(Question question) {
 

  
//I am making false my previously chosen answer
    _answersSummaryList
        .firstWhere((item) => item.id == question.id)
        .answers
        .firstWhere((element) => element.isSelected == true)
        .isSelected = false;

//I m making true what i want answer

    _answersSummaryList
        .firstWhere((item) => item.id == question.id)
        .answers
        .firstWhere((element) => element.id == _answerId)
        .isSelected = true;


//Checking if it has changed here.it is changing

        _answersSummaryList.forEach((element) {.   
          element.answers.forEach((element) {
            print(element.title);
            print(element.isSelected);
          });
    
      }

如果我对列表使用 .remove 函数。它正在与观察者一起在屏幕上运行和删除,但是当我用第一个 Where 更改我的答案时。它不是在屏幕上改变,而是在后面改变。

标签: flutterdartmobx

解决方案


我们知道 mobX 不适用于常规列表,我们有 ObservableList。

而且您的问题模型具有答案列表,因此它不会做出反应。我在 mobX 中的嵌套列表有类似的问题。

这是一个演示解决方案示例。

QuestionListStore 有一个 QuestionStore 列表。我们知道 QuestionStore 有 ObserverableList,它变成了响应式的。

class QuestionListStore = _QuestionListStore with _$QuestionListStore;

abstract class _QuestionListStore with Store {

  @observable
  ObservableList<QuestionStore> questionList =
      ObservableList<QuestionStore>();

  @action
  void addQuestion(Question question){
       QuestionStore questionStore = QuestionStore(
        id: question.id,
        title: question.title, );
       questionList.add(questionStore);
       
       // you can access QuestionStore methods here
       questionStore.addAnswer(// instance of Answer model);
  }

}

class QuestionStore = _QuestionStore with _$QuestionStore;

abstract class _QuestionStore extends Question with Store {

  _QuestionStore ({
    id,
    title,
  }) : super(id: id, title: title)

  @observable
  ObservableList<Answer> answerList = ObservableList<Answer>();
  
  @action
  void addAnswer(Answer answer){
    answerList.add(answer);
  }

}

推荐阅读