承接上一篇的基本型別與Obx綁定
這篇接下來說 List<自訂型別>, enum , Map, 這幾種資料型態
還有除了Obx直接響應外,另一種更新方法
GetBuilder(綁定)和 update(在想要的時間點執行畫面更新)
//List<DataModel>
final _someModelList = <SomeModel>[].obs;
set someModelList(value) => this._someModelList.value = value;
List<SomeModel> get someModelList => this._someModelList.toList();
//Map
final someDict = {}.obs;
//Enum
final _enumSelectState = Rx<SomeEnumState>(SomeEnumState.stateOne);
set enumSelectState(value) => this._enumSelectState.value = value;
get enumSelectState => this._enumSelectState.value;
//簡單定義一下List的自定義型別
class SomeModel {
int id = 0;
String name = "";
bool trueFalse = false;
SomeModel();
SomeModel.fromJson(Map<String, dynamic> json) {
id = json['id'] ?? 0;
name = json['name'] ?? "";
trueFalse = json['trueFalse'] ?? false;
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['name'] = this.name;
data['truealse'] = this.trueFalse;
return data;
}
}
//簡單定義一下enum的幾種type
enum SomeEnumState {
stateOne,
stateTwo,
stateThree,
}
再來資料增加button觸發時更新的方法
addSomeModelList(), enumChanged()
addSomeModelList這個方法裡面先new了 SomeMode()
並add到 someModelList裡 接著在呼叫update()方法更新.
update是GetxController裡面提供的畫面更新方法.
addSomeModelList() {
final someModel = SomeModel()
..id = 55
..name = "itHome"
..trueFalse = true;
_someModelList.add(someModel);
this.update();
}
enumChanged() {
switch (enumSelectState) {
case SomeEnumState.stateOne:
enumSelectState = SomeEnumState.stateTwo;
break;
case SomeEnumState.stateTwo:
enumSelectState = SomeEnumState.stateThree;
break;
case SomeEnumState.stateThree:
enumSelectState = SomeEnumState.stateOne;
break;
}
update(["enum"]);
}
前幾篇用到的是Obx() 如果資料有變化,Widget會直接響應並作更新
如果用的是GetBuilder()則需要呼叫update(),widget才會更新,
所以需要在適合的時間點呼叫update(),
而update()有一個變化型,可以帶入List["id"]對應到
GetBuilder(id: ""), 只針對特定的更新, 達到比較好的效率,
這也就是使用原生StatefulWidgety, setState()在使用時要考慮到的部分,
如果沒有帶入, 則是全部的GetBuilder作更新.
GetBuilder<BindingPageController>(
id: "enum", //對應到BindingPageController64行的 update(["enum"]);
init: controller,
builder: (_) {
return Center(
child: Text(controller.enumSelectState.toString()));
},
),
最後效果如下
下一篇將為大家介紹
GetX something else
(多國語系 螢幕長寬 GetX snackbar)