GetxController GetxBinding ,GetView多个页面的状态的共享,也就是数据的共享,

440 阅读1分钟

1.继承 GetxController

class CountPage extends GetxController {
  var count = 0.obs;
  void inc(){
    count++;
    update();
  }

  List list = [].obs;
  void listAdd(value){
    list.add(value);
   update();
  }

}
//创建控制器实例
CountPage valuePage = Get.put(CountPage());

getView(int index){
  if(index == 0) {
    return  Center(child: ElevatedButton(child: Obx(() => Text('${valuePage.count}')),onPressed: (){
      valuePage.inc();
    },));
  } else if(index == 1){
    return  Center(child: ElevatedButton(child:Obx(() => Text('${valuePage.count}')),onPressed: (){
      valuePage.inc();
    },),);
  } else {
    return Center(child: ElevatedButton(child: Obx(() => Text('${valuePage.count}')),onPressed: (){
      Get.to(StatePage());
    },));
  }
}

StatePage

static CountPage countPage = Get.find();

Obx(() => Text("我是tabbar页面的数据::::${countPage.count}")),

return SingleChildScrollView(child: Column(
    children: [
      SizedBox(height: 30,),
      ElevatedButton(child: Obx(() => Text('${valuePage.count}')),onPressed: (){
        valuePage.inc();
        valuePage.listAdd("${valuePage.list.length}");

      },),
       Obx(() =>
           ListView.builder(physics:NeverScrollableScrollPhysics(), shrinkWrap: true, itemCount:valuePage.list.length, itemBuilder: (context,index) {
            return  Obx(() => Text('${valuePage.list[index]}'));
          }),
        ),
    ],
  ),
);

2.GetxBinding 为了解决每一个都需要实力初始化,全局绑定。

其他地方就可以删除CountPage valuePage = Get.put(CountPage()); 直接find就可以。

GetMaterialApp(
    initialBinding:MyBinding(),
GetMaterialApp(
    initialBinding:MyBinding(),
class MyBinding extends Bindings {
  @override
  void dependencies() {
    Get.lazyPut(() => CountPage());
  }

}

3.GetView为了省去Get.find,使用GetView

//注入CountPage
class SettingPage extends GetView<CountPage> {
 @override
 Widget build(BuildContext context) {
  return Center(
    //使用GetView 省略get.find
    child: Obx(() => Text("数字----->${controller.count}")),
  );
 }

4.因为GetView 是stateless,所以没有statuful的initState GetView处理界面,GetController来处理逻辑。