Flutter Getx 状态管理 --- 响应式状态管理器

发布时间 2024-01-11 14:49:20作者: 鲤斌

状态管理

Get 并不是比任何其他状态管理器更好或更差,而是说你应该分析这些要点以及下面的要点来选择只用
Get,还是与其他状态管理器结合使用。
Get不是其他状态管理器的敌人,因为Get是一个微框架,而不仅仅是一个状态管理器,既可以单独使
用,也可以与其他状态管理器结合使用。
Get有两个不同的状态管理器:响应式状态管理器、简单的状态管理器。

响应式状态管理器

响应式编程可能会让很多人感到陌生,因为它很复杂,但是GetX将响应式编程变得非常简单。
你不需要创建StreamControllers.
你不需要为每个变量创建一个StreamBuilder。
你不需要为每个状态创建一个类。
你不需要为一个初始值创建一个get。
使用 Get 的响应式编程就像使用 setState 一样简单。

响应式状态管理器-计数器

让我们想象一下,你有一个名称变量,并且希望每次你改变它时,所有使用它的小组件都会自动刷新。
这就是你的计数变量。
int _counter = 0;
要想让它变得可观察,你只需要在它的末尾加上".obs"。
RxInt _counter = 0.obs;
而在UI中,当你想显示该值并在值变化时更新页面,只需这样做。
Obx(() => Text("$_counter"));
完整代码
class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key});
  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  RxInt _counter = 0.obs;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("Gex 计数器"),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            const Text(
              'You have pushed the button this many times:',
            ),
            Obx(() => Text("${_counter.value}"))
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          _counter++;
        },
        tooltip: 'Increment',
        child: const Icon(Icons.add),
      ), 
    );
  }
}
 

声明一个响应式变量三种方式

第一种 使用 Rx{Type}。
final name = RxString('');
final isLogged = RxBool(false);
final count = RxInt(0);
final balance = RxDouble(0.0);
final items = RxList<String>([]);
final myMap = RxMap<String, int>({});
第二种是使用 Rx,规定泛型 Rx。
final name = Rx<String>('');
final isLogged = Rx<Bool>(false);
final count = Rx<Int>(0);
final balance = Rx<Double>(0.0);
final number = Rx<Num>(0)
final items = Rx<List<String>>([]);
final myMap = Rx<Map<String, int>>({});
自定义类 - 可以是任何类
final user = Rx<User>();
第三种 更实用、更简单、更可取的方法,只需添加 .obs 作为value的属性。(推荐)
final name = ''.obs;
final isLogged = false.obs;
final count = 0.obs;
final balance = 0.0.obs;
final number = 0.obs;
final items = <String>[].obs;
final myMap = <String, int>{}.obs;
自定义类 - 可以是任何类
final user = User().obs;

监听自定义类数据的变化

1.类里面的属性响应式变化

创建Person 类
import 'package:get/get.dart';
class Person {
// rx 变量
  RxString name = "Jimi".obs;
  RxInt age = 18.obs;
}
获取类属性值以及改变值
class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key});
  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  var person = Person();
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("Getx Obx"),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Obx(() => Text(
                  "我的名字是 ${person.name.value}",
                  style: const TextStyle(color: Colors.red, fontSize: 30),
                ))
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          person.name.value = person.name.value.toUpperCase();
        },
        tooltip: 'Increment',
        child: const Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}

2.整个类的响应式变化

创建Person 类
class Person {
  String name;
  int age;
  Person(this.name, this.age);
}
获取类属性值以及改变值
class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key});
  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  var person = Person("aotoman", 9999).obs;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("Getx Obx"),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Obx(() => Text(
                  "我的名字是 ${person.value.name}",
                  style: const TextStyle(color: Colors.red, fontSize: 30),
                ))
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          person.value.name = person.value.name.toUpperCase(); //转大小

          person.value = person.value; //重新赋值  *必须
        },
        tooltip: 'Increment',
        child: const Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}