GetView介绍
GetView只是对已注册的Controller有一个名为controller的getter的const Stateless的Widget,如果我们只有单个控制器作为依赖项,那我们就可以使用GetView,而不是使用StatelessWidget,并且避免了写Get.Find()。
GetView源码:
abstract class GetView<T> extends StatelessWidget {
const GetView({Key? key}) : super(key: key);
final String? tag = null;
T get controller => GetInstance().find<T>(tag: tag)!;
@override
Widget build(BuildContext context);
}
GetView使用
class CountController extends GetxController {
var count = 0.obs;
void increment() {
count++;
print(count);
}
}
class GetViewAndGetWidgetExample extends GetView<CountController> {
@override
Widget build(BuildContext context) {
Get.put(CountController());
// Get.create(() => CountController());
return Scaffold(
appBar: AppBar(
title: Text("GetX GetView"),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Obx(() => Text(
"count的值为: ${controller?.count}",
style: TextStyle(
color: Colors.red,
fontSize: 30
),
)),
SizedBox(height: 20,),
ElevatedButton(
onPressed: () {
controller.increment();
},
child: Text("点我加1"))
],
),
),
);
}
}
提醒事项:
如果监听控件引用参数没有加入监听(.obs)
会报错
[Get] the improper use of a GetX has been detected.
You should only use GetX or Obx for the specific widget that will be updated.
If you are seeing this error, you probably did not insert any observable variables into GetX/Obx
or insert them outside the scope that GetX considers suitable for an update
(example: GetX => HeavyWidget => variableObservable).
If you need to update a parent widget and a child widget, wrap each one in an Obx/GetX.
GetWidget介绍
GetWidget 与GetView区别在于: 新建与缓存
abstract class GetWidget<S extends GetLifeCycleBase?> extends GetWidgetCache {
const GetWidget({Key? key}) : super(key: key);
@protected
final String? tag = null;
S get controller => GetWidget._cache[this] as S;
// static final _cache = <GetWidget, GetLifeCycleBase>{};
static final _cache = Expando<GetLifeCycleBase>();
@protected
Widget build(BuildContext context);
@override
WidgetCache createWidgetCache() => _GetCache<S>();
}
使用
///在widget调用之前进行初始化
// Get.put(CountController());
// Get.create(() => CountController());
Get.create<CountController?>(() => CountController());
class GetViewAndGetWidgetExample extends GetWidget<CountController> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("GetX GetView"),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Obx(() => Text(
"count的值为: ${controller?.count}",
style: TextStyle(
color: Colors.red,
fontSize: 30
),
)),
SizedBox(height: 20,),
ElevatedButton(
onPressed: () {
controller.increment();
},
child: Text("点我加1"))
],
),
),
);
}
}
使用场景 :
Todo列表,例如一个todo比较复杂 , 可以考虑这样进行重复创建.