這篇位大家介紹Getx的響應式更新,Widget與屬性綁定(int String bool List這幾種型別)
controller部分
在此定義了幾個屬性對應上幾個基本型別(int String bool List)
在初始值後加入.obs即完成.
並加上getter setter, 如果不用get set也可以使用 只是在Widget端需要
controller.property.value 才能取到值, 所以在controller這裡用get包起來.
class BindingPageController extends GetxController {
//String
final _someString = ''.obs;
set someString(value) => this._someString.value = value;
get someString => this._someString.value;
//int
final _someInt = 0.obs;
set someInt(value) => this._someInt.value = value;
get someInt => this._someInt.value;
//bool
final _someBool = false.obs;
set someBool(value) => this._someBool.value = value;
get someBool => this._someBool.value;
//List
final _someBasicList = <String>[].obs;
set someBasicList(value) => this._someBasicList.value = value;
get someBasicList => this._someBasicList.toList();
@override
void onInit() {
super.onInit();
}
addBasicList() {
_someBasicList.add("add");
}
}
Widget部分
Obx(() => Text(controller.屬性)),
使屬性與畫面之間綁定,在此要注意的是
如果在Obx function裡, 如果沒有任何controller的 .obs的屬性,運行時會報錯
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('BindingPage')),
body: SafeArea(
child: SizedBox.expand(
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Obx(() => Center(child: Text('${controller.someString}'))),
Obx(() => Center(child: Text('${controller.someInt}'))),
Obx(() => Center(child: Text('${controller.someBool}'))),
Obx(() {
return Expanded(
flex: 1,
child: ListView(
children: List.generate(controller.someBasicList.length,
(index) {
final title = controller.someBasicList[index];
return Center(child: Text(title));
}),
),
);
},
),
],
),
),
),
);
}
實際畫面
下一篇是 binding(二) 將為大家介紹
List<自定型別>, enum, Map與 GetBuilder的綁定.