【问题标题】:How to make model fields observable in Flutter如何在 Flutter 中使模型字段可观察
【发布时间】:2021-10-26 04:40:43
【问题描述】:

我有一个名为 category 的模型,它有两个字段,用户有一个类别列表以及更新类别名称的内容,用于状态管理 getx 使用

class Category {
 
 String? categoryName;
 bool status;
 
 Category(this.categoryName,this.status);
}

我有一个名为 catList 的可观察列表,用于列表小部件

var catList = <Category>[].obs;

当我更新类别字段时它不会更新

catList[index].categoryName = categoryChangedName.value;

但是如果我更新对象中的项目然后将对象分配给 catList 那么它改变了

catList[index] = Category(categoryChangedName.value, catList[index].status );

我的问题是如何使模型字段可观察,如果我们有更多字段更改,那么这不是正确的方法。

【问题讨论】:

    标签: flutter state-management flutter-getx


    【解决方案1】:

    从 GetX 文档开始,您需要使用方法更新值并调用 update();自定义对象内的方法!

    例如:

    class Controller extends GetxController {
      int counter = 0;
      void increment() {
        counter++;
        update(); // look here!
      }
    }
    

    您的用例可能是......

    class Category {
     
       String? categoryName;
       bool status;
     
       Category(this.categoryName,this.status);
       
       void updateCategoryName(name){
         this.categoryName = name;
         update();
       }
      }
    
      //Use like..
    
     catList[index].updateCaetgoryName = categoryChangedName.value;
    

    【讨论】:

      猜你喜欢
      • 2015-03-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-22
      • 2018-06-28
      • 1970-01-01
      • 2023-02-15
      • 1970-01-01
      相关资源
      最近更新 更多