Getx:响应式数据,实现数据的局部刷新
Flutter官网demo实现计数器
这个demo中,如果要更新_count++
,调用setState
就会重新build
,这样做比较耗费性能,此时可以使用Getx的响应式状态管理器实现局部刷新
import 'package:flutter/material.dart';
class JiShu extends StatefulWidget {
const JiShu({Key? key}):super(key:key);
@override
State<JiShu> createState() => _JiShuState();
}
class _JiShuState extends State<JiShu> {
int _count = 0;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('计数器'),),
body: Column(
children: [
Text('计数器:${_count}'),
ElevatedButton(onPressed: (){
setState(() {
_count++;
});
}, child: Text('计数器++'))
],
),
);
}
}
Getx响应式状态管理器,实现刷新局部数据
Flutter
中无状态组件StatelessWidget
是不能触发计数器的,通过Getx响应式状态管理器
实现了数字的更新
final _count = 0.obs; // 定义响应式状态
Obx(()=> Text('计数器:${_count.value}')), // 通过Obx渲染数据
_count.value++; // 改变数据
// main 文件入口必须使用GetMaterialApp包裹以下
return const GetMaterialApp(
home: JiShu(),
);
import 'package:flutter/material.dart';
import 'package:get/get.dart';
class JiShu extends StatelessWidget {
const JiShu({Key?key}):super(key: key);
@override
Widget build(BuildContext context) {
final _count = 0.obs;
final _name = '张三'.obs;
return Scaffold(
appBar: AppBar(title: Text('计数器'),),
body: Column(
children: [
Obx(()=> Text('计数器:${_count.value},姓名:${_name.value}')),
ElevatedButton(onPressed: (){
_count.value++;
_name.value = '李四';
}, child: Text('计数器++'))
],
),
);
}
}
响应式数据定义的方式
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;
自定义响应式类
class Animal {
String name;
int age;
Animal(this.name,this.age);
}
// 下个页面中使用这个类
import 'animal.dart';
var _animal = Animal('张三', 30).obs;
...
Obx(()=> Text('计数器:${_animal.value.name},年龄:${_animal.value.age}')),
ElevatedButton(onPressed: (){
_animal.value.name = '李四';
_animal.value.age = 40;
_animal.value = _animal.value;
}, child: Text('修改自定义类响应式')),