Flutter之不使用GetView 2025-04-17 周
2025-04-16 本文已影响0人
松哥888
吸引人的介绍
在GetX的官网,对于GetView的介绍非常好。说是可以直接使用controller
class AwesomeController extends GetController {
final String title = 'My Awesome View';
}
// ALWAYS remember to pass the `Type` you used to register your controller!
class AwesomeView extends GetView<AwesomeController> {
@override
Widget build(BuildContext context) {
return Container(
padding: EdgeInsets.all(20),
child: Text(controller.title), // just call `controller.something`
);
}
}
实际的坑
- 上面的代码是不能实际使用的,还要在其他地方执行绑定
Get.put(AwesomeController());
绑定函数会返回对应的controller,存成成员变量就可以,那么提供一个默认的controller又有什么意义。
-
build方法其实是不能变的,在controller中修改数据,然后调用update()不能让界面重绘。需要在外面再套一层GetBuild才行。这是最容易忽略的地方,但是GetView在这里并没有什么改进。
-
至于说Obx之类的,还是省省吧。简单做个Demo还行,实际工程中,脑残才会用。
-
tag是固定字符串,还不是变量,直接导致不能使用。加tag是为了多个controller实例,固定字符串和null有什么区别?
源码
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);
}
其实就加了个find方法,真的很水。tag作为变量还行,还给个初始值,弱智的做法。