[英]Using an observable variable without a controller in Flutter GetX
Something that I didn't completely understand about the Get package is whether it is always required to put the observable variables in a controller. For example, this case works:我对 Get package 没有完全理解的是是否总是需要将可观察变量放在 controller 中。例如,这种情况有效:
import 'package:flutter/material.dart'; import 'package:get/get.dart'; void main() => runApp(App()); class App extends StatelessWidget { final isTrue = true.obs; @override Widget build(BuildContext context) { return MaterialApp( title: 'Demo', theme: ThemeData( visualDensity: VisualDensity.adaptivePlatformDensity, ), home: Scaffold( body: Center( child: Obx( () => FlatButton( color: isTrue.value? Colors.blue: Colors.red, child: Text('Hey'), onPressed: () => isTrue.value =.isTrue,value, ), ), ), ); ); } }
But would there be leaks/problems, because of this and is a GetXController necessary in this situation?但是会不会有泄漏/问题,因此在这种情况下是否需要 GetXController?
So as @Baker explained with his comments, the obs streams should be destroyed through the GetXControllers and they will persist in memory, if used independently in a stateless widget.因此,正如@Baker 在他的评论中解释的那样,obs 流应该通过 GetXControllers 销毁,如果在无状态小部件中独立使用,它们将保留在 memory 中。
Yes, you can achieve using an Rx<T>
observable in your UI, without using any GetxController
, with the ObxValue
widget which comes with the Getx
package:是的,您可以在 UI 中使用Rx<T>
observable 来实现,而无需使用任何GetxController
,使用ObxValue
package 附带的Getx
小部件:
you can use it like this:你可以这样使用它:
ObxValue<RxInt>(
(data) => GestureDetector(
onTap: () {
data.value++;
},
child: Text("${data.value}"),
),
0.obs,
),
as you see, you need to specify the type of the ObxValue
's Rx<T>
, in my case I specified RxInt
, then its an initial value which is 0.obs
, and in the builder, you can return a widget and manage the value of it, and it will update automatically.如您所见,您需要指定ObxValue
的Rx<T>
的类型,在我的例子中我指定RxInt
,然后它的初始值为0.obs
,在构建器中,您可以返回一个小部件并管理它的值,它会自动更新。
Note: the ObxValue
manage automatically it's lifecycle, when the widget is moved from the tree ( disposed ), also the observable will dispose / close automatically.注意: ObxValue
自动管理它的生命周期,当小部件从树中移动(处置)时,observable 也会自动处置/关闭。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.