安装
将 GetX 添加到你的 pubspec.yaml 文件中
dependencies:
get: ^4.6.5
在需要用到的文件中导入,它将被使用。
import 'package:get/get.dart';
介绍
响应式编程可能会让很多人感到陌生,因为它很复杂,但是GetX将响应式编程变得非常简单。
你不需要创建StreamControllers.
你不需要为每个变量创建一个StreamBuilder。
你不需要为每个状态创建一个类。
你不需要为一个初始值创建一个get。
使用 Get 的响应式编程就像使用 setState 一样简单。
定义Obx变量的三种方式
// 第一种 使用 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<Type>。
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;
代码
import 'package:flutter/material.dart';
import 'package:get/get.dart';
void main(){
return runApp(MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
Widget build(BuildContext context) {
return GetMaterialApp(
title: "Obx使用",
home: ObxCountExample(),
);
}
}
class ObxCountExample extends StatelessWidget {
// RxInt count = RxInt(0); // 第一种
// var count = Rx<double>(0); // 第二种
var count = 0.obs;// 第三种
void increment(){
count++;
}
Widget build(BuildContext context) {
return Container(
child: Scaffold(
appBar: AppBar(
title: Text("Obx使用"),
),
body: Center(
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
children: [
Obx(()=>Text(
"count的值为:$count",
style: TextStyle(
fontSize: 20,
color: Colors.red
),
)),
SizedBox(height: 20,),
ElevatedButton(onPressed: ()=>{
increment()
}, child: Text("点击+1"))
],
),
),
),
);
}
}
自定义类
import 'package:flutter/material.dart';
import 'package:get/get.dart';
void main(){
return runApp(MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
Widget build(BuildContext context) {
return GetMaterialApp(
title: "自定义",
home: Home(),
);
}
}
class Home extends StatelessWidget {
var teacher = Teacher();
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("自定义"),
),
body: Center(
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
children: [
Obx(()=>Text(
"我的名字是${teacher.name.value}"
)),
SizedBox(height: 20,),
ElevatedButton(onPressed: ()=>{
teacher.name.value = teacher.name.value.toUpperCase()
}, child: Text("转换为大写"))
],
),
),
);
}
}
// 自定义
class Teacher {
var name = "aaaabbbbccccddd".obs;
var age = 18.obs;
}