Flutter中使用get

get的优势:
路由管理、状态管理

项目中引入
将Get添加到您的pubspec.yaml文件:

dependencies:
  get: ^4.6.5

导入要使用的文件:

import 'package:get/get.dart';

GetX地址

  • Github:https://github.com/jonataslaw/getx
  • Pub:https://pub.dev/packages/get

主入口配置
只需要将MaterialApp改成GetMaterialApp即可

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return GetMaterialApp(
      home: CounterGetPage(),
    );
  }
}

页面跳转

Get.to(NextScreen());

通过命名跳转

Get.toNamed('/details');

返回上一个页面

Get.back();

跳转下一个页面,并关闭当前页面,用于闪屏、登录页:

Get.off(NextScreen());

跳转下一个页面,并关闭其他所有页面:

Get.offAll(NextScreen());

简单状态管理 计数器示例:
logic层:处理页面逻辑的

class CounterEasyLogic extends GetxController {
  var count = 0;

  void increase() {
    ++count;
    update();
  }
}

view层:

class CounterEasyPage extends StatelessWidget {
  final logic = Get.put(CounterEasyLogic());

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('计数器-简单式')),
      body: Center(
        child: GetBuilder<CounterEasyLogic>(builder: (logic) {
          return Text(
            '点击了 ${logic.count} 次',
            style: TextStyle(fontSize: 30.0),
          );
        }),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () => logic.increase(),
        child: Icon(Icons.add),
      ),
    );
  }
}

响应式状态管理
logic层:

  • 这里变量数值后写.obs操作,是说明定义了该变量为响应式变量,当该变量数值变化时,页面的刷新方法将自动刷新
  • 基础类型,List,类都可以加.obs,使其变成响应式变量
class CounterRxLogic extends GetxController {
  var count = 0.obs;

  ///自增
  void increase() => ++count;
}

View层:

class CounterRxPage extends StatelessWidget {
  final logic = Get.put(CounterRxLogic());

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('计数器-响应式')),
      body: Center(
        child: Obx(() {
          return Text(
            '点击了 ${logic.count.value} 次',
            style: TextStyle(fontSize: 30.0),
          );
        }),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () => logic.increase(),
        child: Icon(Icons.add),
      ),
    );
  }
}

整个类对象设置为响应类型:
当你改变了类其中一个变量,然后执行更新操作,只要包裹了该响应类变量的Obx(),都会实行刷新操作,将整个类设置响应类型,需要结合实际场景使用

// model
// 我们将使整个类成为可观察的,而不是每个属性。
class User{
    User({this.name = '', this.age = 0});
    String name;
    int age;
}

// controller
final user = User().obs;
//当你需要更新user变量时。
user.update( (user) { // 这个参数是你要更新的类本身。
    user.name = 'Jonny';
    user.age = 18;
});
// 更新user变量的另一种方式。
user(User(name: 'João', age: 35));

// view
Obx(()=> Text("Name ${user.value.name}: Age: ${user.value.age}"));
// 你也可以不使用.value来访问模型值。
user().name; // 注意是user变量,而不是类变量(首字母是小写的)。

猜你喜欢

转载自blog.csdn.net/Billy_Zuo/article/details/130324185