GetX中共有4 种状态管理, 分别是Obx, GetX, GetBuilder, ValueBuilder
但最常用的是 Obx 和 GetBuilder
1 Obx
如果你的变量是.obs的,那么我们就使用Obx(()=>),它会在变量变更时自动刷新view
注意: 只能对字符串,数字,布尔这种非容器的数据类型用obs和Obx
class StateObxView extends StatelessWidget {const StateObxView({Key? key}) : super(key: key);@overrideWidget build(BuildContext context) {// 在变量末尾添加.obs, 使得该变量可被观察final count = 0.obs;return Scaffold(appBar: AppBar(title: Text("Obx"),),body: Center(child: Column(children: [// 当你想显示该值实时的变化, 用Obx包裹Obx(() => Text("count1 -> $count")),ElevatedButton(onPressed: () {count.value++;},child: Text("add"))],)),);}}
2 GetBuilder
如果你的变量不是.obs的,那么我们就使用GetBuilder
如果你的变量是容器类型, 比如List, Map, 就必须用GetBuilder
因为子元素类型都要设置obs, 才能被Obx监测到
class HomeController extends GetxController {int count = 0;void increment() {count++;update();}}
class HomePage extends GetView<HomeController> {HomePage({Key? key}) : super(key: key);@overrideWidget build(BuildContext context) {return BaseScaffold(appBar: MyAppBar(centerTitle: true,title: MyTitle('首页'),leadingType: AppBarBackType.None,),body: Container(child: GetBuilder<HomeController>(builder: (_) {return Center(child: Text(controller.count.toString()));}),),);}}
