Flutter GetX 第一个空值

4

亲爱的互联网朋友们,感谢使用getx,我有一个关于getx rx flow和getx initial的问题。虽然我在rxjs方面是一位老手,但我对getx还很陌生。在rxjs中,只能通过.next(value)发出值。

我的问题是:如何通过任何方式避免发出初始null值?我基本的理解是,在UI或widget上,Obx()Getx<Xyz>()GetBuilder<Xyz>()只会发出值。

以下是与此问题相关的一些片段:

[3]中的此特定行 Text('' + _identity.value.profile.name)) 总是首先为空值 [3],几毫秒后,服务器的响应被设置并且一切正常。那么,如何避免第一个null值发出,即异常?因为这是我根据通用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: UI

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中添加空值检查确实没有意义,这只是我个人(IMHO)的看法,不符合Redux的设计思想。

2个回答

0

我发现实现这个的最佳方式是getxrx_widgets的混合使用。

enter image description here

你可以在 GitHub 上获取代码


-1

文本不能赋予空值,您应该使用?.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;

可以进行空值检查,但我的问题是如何避免最初的空值发射始终发生。 - 4F2E4A2E

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接