如何解决Flutter getx 第一个空值
亲爱的互联网,您好,感谢您提供 getx,
我有一个关于 getx rx 流程和/ getx 初始值的问题。我是 getx 的新手,但我是 rxjs 的老手,在那里你得到的值只在 .next(value)
;
我的问题是:如何 - 无论如何[4] - 避免初始空值的发射?
我的基本理解是,在 UI 或小部件上,Obx()
、Getx<Xyz>()
或 GetBuilder<Xyz>()
只会用于值发射。
这里是关于这个问题的一些片段:
来自 [3] Text('' + _identity.value.profile.name))
的这一行总是首先导致 null [3],几毫秒后,来自服务器的响应被设置,一切都很好。
那么,如何避免第一个空值发射,ergo 异常?因为这是我基于一般 redux 体验的期望。
1:https://github.com/jonataslaw/getx/blob/master/lib/get_rx/src/rx_types/rx_core/rx_impl.dart#L371
2:控制器
final Rx<UserDataProfile> _userDataProfile = UserDataProfile().obs;
[...] after a few seconds milliseconds
_userDataProfile.value(xyzValue);
3:界面
class DetailScreen extends StatelessWidget {
final logger = LoggingService().logger;
@override
Widget build(BuildContext context) {
final dataService = Get.find<DataService>();
final _identity = dataService.identity();
return Scaffold(
appBar: AppBar(
title: Obx(() => Text('' + _identity.value.profile.name)),leading: IconButton(
icon: Icon(Icons.arrow_back),onPressed: () {
Get.back();
},),);
}
}
3:异常
======== Exception caught by widgets library =======================================================
The following NoSuchMethodError was thrown building Obx(dirty,state: _ObxState#b3490):
The getter 'name' was called on null.
Receiver: null
Tried calling: name
4:添加空值检查真的没有意义,这只是 - 恕我直言 - 不是 redux 的方式。
解决方法
关于如何实现这一点,我能找到的最好方法是结合使用 getx 和 rx_widgets
你可以抓住code here on github
,Text 不能被赋予空值,您应该使用 ?.name
来防止这种情况并在为空时提供默认值,例如:
class DetailScreen extends StatelessWidget {
final logger = LoggingService().logger;
@override
Widget build(BuildContext context) {
final dataService = Get.find<DataService>();
final _identity = dataService.identity();
return Scaffold(
appBar: AppBar(
title: Obx(() => Text('' + (_identity.value.profile?.name ?? ''))),// here
leading: IconButton(
icon: Icon(Icons.arrow_back),onPressed: () {
Get.back();
},),);
}
}
或添加默认值以防止空值:
Rx<UserDataProfile> _userDataProfile = UserDataProfile(name: '').obs;
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。